序列化和反序列化,objectMapper 详解


ObjectMapper 是 Jackson 库中的核心类,用于在 Java 对象和 JSON 数据之间进行序列化(将 Java 对象转换为 JSON)和反序列化(将 JSON 转换为 Java 对象)。 ObjectMapper 提供了丰富的配置选项和功能,可以帮助开发者处理复杂的 JSON 数据结构。

1、主要功能

  • 序列化: 将 Java 对象转换为 JSON 字符串。
  • 反序列化: 将 JSON 字符串转换为 Java 对象。

2、配置与自定义: 提供了一系列注解和配置方法,允许对序列化和反序列化过程进行高度定制。

常用方法

  • writeValueAsString(Object value): 将 Java 对象序列化为 JSON 字符串。
  • readValue(String content, Class<T> valueType): 将 JSON 字符串反序列化为 Java 对象。
  • writeValue(File resultFile, Object value): 将 Java 对象序列化为 JSON 并写入文件。
  • readTree(String content): 将 JSON 字符串解析为 JsonNode 树,可以方便地进行树形结构操作。
  • configure(DeserializationFeature feature, boolean state): 配置反序列化特性,如是否允许未知属性等。
  • 常见的配置
	//创建ObjectMapper对象
    mapper = new ObjectMapper()
    //configure方法 配置一些需要的参数
    // 转换为格式化的json 显示出来的格式美化
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
   //序列化的时候序列对象的那些属性  
   //JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化 
   //JsonInclude.Include.ALWAYS      所有属性
   //JsonInclude.Include.NON_EMPTY   属性为 空(“”) 或者为 NULL 都不序列化 
   //JsonInclude.Include.NON_NULL    属性为NULL 不序列化
   mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);  
    //反序列化时,遇到未知属性会不会报错 
    //true - 遇到没有的属性就报错 false - 没有的属性不会管,不会报错
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //如果是空对象的时候,不抛异常  
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
    // 忽略 transient 修饰的属性
    mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
    //修改序列化后日期格式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);  
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
   //处理不同的时区偏移格式
   mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   mapper.registerModule(new JavaTimeModule());

3、例子

3.1. 简单的序列化与反序列化

import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // 创建一个简单的 Java 对象
        User user = new User("John", 30);

        // 序列化:Java 对象 -> JSON 字符串
        String jsonString = objectMapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + jsonString);

        // 反序列化:JSON 字符串 -> Java 对象
        User deserializedUser = objectMapper.readValue(jsonString, User.class);
        System.out.println("Deserialized User: " + deserializedUser);
    }
}

class User {
    private String name;
    private int age;

    // 构造函数、getters 和 setters
    public User() {}

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

    // getter 和 setter

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}

3.2. 使用注解自定义序列化和反序列化

通过 @JsonProperty 注解,可以指定 JSON 字段名与 Java 字段名之间的映射。

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

public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // 创建带有自定义注解的 Java 对象
        Customer customer = new Customer("Alice", "New York");

        // 序列化
        String jsonString = objectMapper.writeValueAsString(customer);
        System.out.println("Serialized JSON: " + jsonString);

        // 反序列化
        Customer deserializedCustomer = objectMapper.readValue(jsonString, Customer.class);
        System.out.println("Deserialized Customer: " + deserializedCustomer);
    }
}

class Customer {
    @JsonProperty("customer_name")
    private String name;

    @JsonProperty("customer_city")
    private String city;

    // 构造函数、getters 和 setters
    public Customer() {}

    public Customer(String name, String city) {
        this.name = name;
        this.city = city;
    }

    @Override
    public String toString() {
        return "Customer{name='" + name + "', city='" + city + "'}";
    }
}

输出结果:

Serialized JSON: {"customer_name":"Alice","customer_city":"New York"}
Deserialized Customer: Customer{name='Alice', city='New York'}

ObjectMapper 是 Jackson 中非常强大的工具,提供了灵活且可配置的序列化和反序列化功能。通过注解和配置选项,开发者可以轻松处理复杂的 JSON 数据结构,并将其映射到 Java 对象中进行处理。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值