转载

Jackson ObjectMapper总结

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
复制代码

该依赖同时会将如下库添加到项目路径中:

  • jackson-annotations-2.9.8.jar
  • jackson-core-2.9.8.jar
  • jackson-databind-2.9.8.jar

2. 序列化和反序列化

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {

    private String color;
    private String type;
}
复制代码

2.1 Java对象序列化为Json

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Car car = new Car("yellow", "renault");
        objectMapper.writeValue(new File("target/car.json"), car);

    }
}
复制代码

输出结果 car.json:

{"color":"yellow","type":"renault"}
复制代码

writeValueAsString: 将生成的JSON转化为字符串

//{"color":"yellow","type":"renault"}
String carAsString = objectMapper.writeValueAsString(car);
复制代码

writeValueAsBytes: 将生成的JSON转化为字节数组

2.2 JSON反序列化为Java对象

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "{ /"color/" : /"Black/", /"type/" : /"BMW/"}";
        Car car = objectMapper.readValue(json, Car.class);
        System.out.println(car);
    }
}

//输出结果:Car(color=Black, type=BMW)
复制代码

readValue()函数还接受其他形式的输入,例如包含JSON字符串的文件:

ObjectMapper objectMapper = new ObjectMapper();
        String json = "{ /"color/" : /"Black/", /"type/" : /"BMW/"}";
        Car car = objectMapper.readValue(new File("target/json_car.json"), Car.class);
        System.out.println(car);

//输出Car(color=yellow, type=renault)    
复制代码

或者URL

Car car = objectMapper.readValue(new URL("target/json_car.json"), Car.class);
复制代码

2.3 JSON 反序列化为Jackson JsonNode

同样的,JSON可以被解析为JsonNode对象,从某一个具体的节点获取数据。

String json = "{ /"color/" : /"Black/", /"type/" : /"FIAT/" }";
JsonNode jsonNode = objectMapper.readTree(json);
String color = jsonNode.get("color").asText();
// Output: color -> Black
复制代码

2.4 JSON数组反序列化为Java List

通过使用 TypeReference 可以将数组形式的JSON反序列化为Java 数组

String jsonCarArray =
        "[{ /"color/" : /"Black/", /"type/" : /"BMW/" }, 
        { /"color/" : /"Red/", /"type/" : /"FIAT/" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, 
    new TypeReference<List<Car>>(){});

//[Car(color=Black, type=BMW), Car(color=Red, type=FIAT)]
System.out.println(listCar);
复制代码

2.5 JSON字符串反序列化为Java Map

String json = "{ /"color/" : /"Black/", /"type/" : /"BMW/" }";
Map<String, Object> map
        = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
        
//{color=Black, type=BMW}        
System.out.println(map);
复制代码

3. 高级特性

Jackson 库的一个强大之处在于可以对序列化、反序列化进行定制。

3.1 设置序列化、反序列化特性

默认情况下,当JSON字符串包含Java类没有的属性时,反序列化就会失败。

String jsonString
            = "{ /"color/" : /"Black/", /"type/" : /"Fiat/", /"year/" : /"1970/" }";

//UnrecognizedPropertyException
Car car = objectMapper.readValue(jsonString, Car.class);
复制代码

通过设置方法我们可以改变默认的行为使其忽略新的字段属性。

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonString
        = "{ /"color/" : /"Black/", /"type/" : /"Fiat/", /"year/" : /"1970/" }";
Car car = objectMapper.readValue(jsonString, Car.class);
//Car(color=Black, type=Fiat)
System.out.println(car);
复制代码

类似的 FAIL_ON_NULL_FOR_PRIMITIVES : 允许基本类型的值为null。

配置方式为

objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
复制代码

FAIL_ON_NUMBERS_FOR_ENUM :控制枚举值是否被允许序列化/反序列化为数字

配置方式为:

objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false)
复制代码

更多的配置方式详见https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features

3.4 处理集合

DeserializationFeature类提供的另一个小而有用的功能是能够从JSON数组响应生成我们想要的集合类型的功能。

例如,我们可以将结果生成为数组:

String jsonCarArray =
        "[{ /"color/" : /"Black/", /"type/" : /"BMW/" }, { /"color/" : /"Red/", /"type/" : /"FIAT/" }]";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class);
// Car(color=Black, type=BMW)
//Car(color=Red, type=FIAT)
for (Car car : cars) {
    System.out.println(car);
}
复制代码

Or as a List:

String jsonCarArray =
        "[{ /"color/" : /"Black/", /"type/" : /"BMW/" }, { /"color/" : /"Red/", /"type/" : /"FIAT/" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
// [Car(color=Black, type=BMW), Car(color=Red, type=FIAT)]
System.out.println(listCar);
复制代码

处理集合的更多资料详见https://www.baeldung.com/jackson-collection-array

原文  https://juejin.im/post/5d9733a26fb9a04e38584387
正文到此结束
Loading...