📜  Jackson教程(1)

📅  最后修改于: 2023-12-03 15:31:27.740000             🧑  作者: Mango

Jackson教程

Jackson 是一个流行的Java 序列化/ 反序列化库,它允许开发者将Java对象序列化为JSON格式,或反序列化JSON字符串为Java对象,而且性能比较高,用法简单,是开发者在Java项目中处理JSON数据的理想选择。

基本使用
1. 添加Maven依赖

将以下代码加入项目的 pom.xml 文件中。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
2. 序列化Java对象为JSON
ObjectMapper mapper = new ObjectMapper();
MyObject obj = new MyObject();
String json = mapper.writeValueAsString(obj);
System.out.println(json);
3. 反序列化JSON为Java对象
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"张三\",\"age\":20}";
MyObject obj = mapper.readValue(json, MyObject.class);
System.out.println(obj);
具体用例

这里将介绍常用的一些 Jackson 应用场景。

1. 处理日期类型
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(dateFormat);
MyObject obj = new MyObject();
String json = mapper.writeValueAsString(obj);
System.out.println(json);
2. 处理null值
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
MyObject obj = new MyObject();
String json = mapper.writeValueAsString(obj);
System.out.println(json);
3. 处理自定义类型
@JsonSerialize(using = MyObjectSerializer.class)
@JsonDeserialize(using = MyObjectDeserializer.class)
public class MyObject {
    private String name;
    private int age;
    // getters and setters
}
public class MyObjectSerializer extends JsonSerializer<MyObject> {
    @Override
    public void serialize(MyObject value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("myName", value.getName());
        gen.writeNumberField("myAge", value.getAge());
        gen.writeEndObject();
    }
}
public class MyObjectDeserializer extends JsonDeserializer<MyObject> {
    @Override
    public MyObject deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        String name = node.get("myName").asText();
        int age = node.get("myAge").asInt();
        MyObject obj = new MyObject();
        obj.setName(name);
        obj.setAge(age);
        return obj;
    }
}
总结

本文主要介绍了 Jackson 序列化/反序列化库的基本用法、及其在具体应用场景下的示例。在实际开发中,可以灵活运用这些技巧,提高开发效率,缩小代码量。