当前位置: 首页 > article >正文

Java中使用Jackson教程

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

一、导入依赖

<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);


http://www.kler.cn/a/328451.html

相关文章:

  • 《探索 C++:一门强大且多功能的编程语言》
  • HTML and CSS Support HTML 和 CSS 支持
  • vue3 路由写法及传参方式 !超详细
  • Java——并发工具类库线程安全问题
  • 十二:HTTP错误响应码:理解与应对
  • 数据处理与统计分析——05-Pandas中DataFrame的方法、属性、索引等一系列操作
  • C语言、Eazy_x——井字棋
  • 巧用时间换空间:解读 ArcGraph 如何灵活应对有限内存下的图分析
  • TDEngine在煤矿综采管控平台中的应用
  • mysql之函数
  • 循环程序结构课堂练习题解
  • 嵌入式 ADC基础知识
  • Unity DOTS System与SystemGroup概述
  • 网络原理-传输层UDP
  • React【vite使用模块化css】
  • 在 Git 中处理分开提交的文件改动,以便更好地管理版本控制
  • 【30天玩转python】数据分析与可视化
  • P3952 [NOIP2017 提高组] 时间复杂度
  • leetcode:380. O(1) 时间插入、删除和获取随机元素
  • 课设实验-数据结构-线性表-手机销售
  • Android 通过自定义注解实现Activity间跳转时登录路由的自动拦截
  • 【React】入门Day01 —— 从基础概念到实战应用
  • HIVE优化系列之数据倾斜
  • 数据库课程设计案例:在线教育管理系统
  • 51单片机学习第六课---B站UP主江协科技
  • 【STM32单片机_(HAL库)】4-4【定时器TIM】脉冲计数配置步骤及实验