Java中使用Jackson教程

本文链接:Java中的Jackson:高级进阶篇_java jackson-****博客

一、导入依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

二、用法

2.1 基础使用

import com.fasterxml.jackson.databind.ObjectMapper;

public class BasicJacksonExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // 序列化Java对象为JSON字符串
        User user = new User("John Doe", 30);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"name":"John Doe","age":30}

        // 反序列化JSON字符串为Java对象
        String json = "{\"name\":\"Jane Doe\",\"age\":25}";
        User userFromJson = mapper.readValue(json, User.class);
        System.out.println(userFromJson.getName()); // 输出: Jane Doe
    }
}

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.2 灵活地控制JSON输出的格式

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

public class JsonFormatExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // 设置输出格式为漂亮打印
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        
        User user = new User("John Doe", 30);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser);
    }
}

2.3 Jackson提供了多种方式来控制序列化行为,比如忽略空字段、忽略未知字段等

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@JsonIgnoreProperties(ignoreUnknown = true)
class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class SerializationControlExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        User user = new User("John Doe", 30);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"name":"John Doe","age":30}

        // 反序列化时忽略未知字段
        String json = "{\"name\":\"Jane Doe\",\"age\":25,\"unknown\":\"value\"}";
        User userFromJson = mapper.readValue(json, User.class);
        System.out.println(userFromJson.getName()); // 输出: Jane Doe
    }
}

2.4 Jackson支持使用注解来标注对象上的JSON元数据

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

class User {
    @JsonProperty("full_name")
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class AnnotationExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        User user = new User("John Doe", 30);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"full_name":"John Doe","age":30}

        // 反序列化JSON字符串为Java对象
        String json = "{\"full_name\":\"Jane Doe\",\"age\":25}";
        User userFromJson = mapper.readValue(json, User.class);
        System.out.println(userFromJson.getName()); // 输出: Jane Doe
    }
}

2.5 Jackson允许我们自定义序列化器来控制特定类型的序列化行为

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class CustomSerializerExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // 注册自定义序列化器
        SimpleModule module = new SimpleModule();
        module.addSerializer(User.class, new UserSerializer());
        mapper.registerModule(module);
        
        User user = new User("John Doe", 30);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"name":"John Doe","age":30}
    }
    
    static class UserSerializer extends JsonSerializer<User> {
        @Override
        public void serialize(User value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeStartObject();
            gen.writeStringField("name", value.getName());
            gen.writeNumberField("age", value.getAge());
            gen.writeEndObject();
        }
    }
}

2.6 Jackson支持枚举类型的序列化和反序列化

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

enum Gender {
    MALE, FEMALE, OTHER
}

class User {
    private String name;
    private Gender gender;

    public User(String name, Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }
}

public class EnumHandlingExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        User user = new User("John Doe", Gender.MALE);
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"name":"John Doe","gender":"MALE"}

        // 反序列化JSON字符串为Java对象
        String json = "{\"name\":\"Jane Doe\",\"gender\":\"FEMALE\"}";
        User userFromJson = mapper.readValue(json, User.class);
        System.out.println(userFromJson.getName()); // 输出: Jane Doe
    }
}

 2.7 Jackson支持处理日期类型

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.Date;

class User {
    private String name;
    private Date birthDate;

    @JsonFormat(pattern = "yyyy-MM-dd")
    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class DateHandlingExample {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        User user = new User();
        user.setName("John Doe");
        user.setBirthDate(new Date());
        
        String jsonUser = mapper.writeValueAsString(user);
        System.out.println(jsonUser); // 输出: {"name":"John Doe","birthDate":"2024-08-07"}
    }
}

三、使用注意事项

3.1 使用时不一定将全部字段和bean对应,比如新建的bean只取json中一个字段也可以,需要加上@JsonIgnoreProperties(ignoreUnknown = true) 注解

public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Test1 t1 = new Test1("ds", true);
        Test t = new Test("cd", t1);
        String param = mapper.writeValueAsString(t);
        System.out.println(param);
        Test2 test = mapper.readValue(param, Test2.class);
        System.out.println(test);
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    static class Test2 {
        private String a1;
        public Test2() {
        }

        public Test2(String a1) {
            this.a1 = a1;
        }
    }

    @Data
    static class Test {
        private String a1;
        private Test1 a2;

        public Test() {
        }

        public Test(String a1, Test1 a2) {
            this.a1 = a1;
            this.a2 = a2;
        }
    }

    @Data
    static class Test1 {
        private String a1;
        private boolean a2;

        public Test1() {
        }

        public Test1(String a1, boolean a2) {
            this.a1 = a1;
            this.a2 = a2;
        }
    }

3.2 在进行复杂的、多层的网络传输中,为了避免传输中String(多次转义、丢失符号等)出错,建议使用byte[] 

byte[] param = objectMapper.writeValueAsBytes(checkWarnDTO);

上一篇:react 前端框架中的 三层(service,model,index)具体操作


下一篇:彻底连接pip工具