利用ObjectMapper转换json和对象

苏鸿志
2023-12-01
将对象转成你想要的对象,除了JSONObject.parseObject外,可以用ObjectMapper

1、添加jackson库

如果是maven工程,需要在pom.xml中添加jackson的依赖:

  1. <dependency>

  2. <groupId>com.fasterxml.jackson.core</groupId>

  3. <artifactId>jackson-databind</artifactId>

  4. <version>2.8.3</version>

  5. </dependency>

用到jackson的类中需要引入:

  1. import com.fasterxml.jackson.databind.ObjectMapper;

  2. import com.fasterxml.jackson.databind.DeserializationFeature;

2、json转object

比如本例中是YourJson(json类型字符串)需要转化为YourClass类(自定义的类)的实例:

  1. ObjectMapper objectMapper = new ObjectMapper();

  2. YourClass class = objectMapper.readValue(YourJson, YourClass.class);

如果json中有新增的字段并且是YourClass类中不存在的,则会转换错误

1)需要加上如下语句:

这种方法的好处是不用改变要转化的类,即本例的YourClass。(如果YourClass不是你维护的,或者不可修改的,可以用这个方法)

  1. ObjectMapper objectMapper = new ObjectMapper();

  2. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  3. YourClass class = objectMapper.readValue(YourJson.toString(), YourClass.class);

2)jackson库还提供了注解方法,用在class级别上:

  1. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

  2. @JsonIgnoreProperties(ignoreUnknown = true)

  3. public class YourClass {

  4. ...

  5. }

3、object转json

本例中是YourClass对象需要转化为json:

  1. import com.fasterxml.jackson.databind.ObjectMapper;

  2.  
  3. ObjectMapper objectMapper = new ObjectMapper();

  4. YourClass yourClass = new YourClass();

  5. String json = objectMapper.writeValueAsString(yourClass);

 

转自:https://blog.csdn.net/u013174217/article/details/53924436

 类似资料: