ObjectMapper的module简单使用

可以把module理解为给ObjectMapper添加自定义的功能

Person 类

我们先看下面这个Person类,里面有个Date类型的属性,我们想写出时间的时候,写出来的样子是:yyyy-MM-dd HH:mm:ss。这里我们不用@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”)(类似于有些类在源码里面,我们根本改不了它们),我们尝试用ObjectMapper来写。

@Data
public class Person {

    private String name;

    private Integer age;

    private Date date;

	
    public Person() {
    }

    public Person(String name, Integer age,Date date) {
        this.name = name;
        this.age = age;
        this.date = date;
    }

}

ObjectMapper测试1

发现jackson是能够正常写出时间,并且读取时间的。但是,这个时间戳并不具有可读性,不够直观。所以,下面尝试使用jackson的module来扩展功能

public static void main(String[] args) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
  
    Person person = new Person("zzhua", 19, new Date());
    System.out.println(mapper.writeValueAsString(person));

    Object o = mapper.readerFor(Person.class).readValue("{\"name\":\"zzhua\",\"age\":19,\"date\":1682518824158}");
    System.out.println(o);

}

/*输出:
	{"name":"zzhua","age":19,"date":1682518854568}
	Person(name=zzhua, age=19, date=Wed Apr 26 22:20:24 CST 2023)
*/

ObjectMapper测试2

通过给mapper添加module,在module中可以为指定的类型添加序列化器和反序列化器,就可以实现相当于自定义序列化和反序列化的效果。module中除了这种功能之外,还有很多其它的功能

public static void main(String[] args) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    
    SimpleModule simpleModule = new SimpleModule();
    
    simpleModule.addSerializer(Date.class, new DateJsonSerializer());
    
    simpleModule.addDeserializer(Date.class, new DateJsonDeserializer());
    
    mapper.registerModule(simpleModule);

    Person person = new Person("zzhua", 19, new Date());
    System.out.println(mapper.writeValueAsString(person));

    Object o = mapper.readerFor(Person.class).readValue("{\"name\":\"zzhua\",\"age\":19,\"date\":\"2023-04-26 22:25:57\"}");
    System.out.println(o);

}

/* 输出:
	{"name":"zzhua","age":19,"date":"2023-04-26 22:26:14"}
	Person(name=zzhua, age=19, date=Wed Apr 26 22:25:57 CST 2023)
*/

DateJsonSerializer

写一个Date类型的序列化器

public class DateJsonSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (value != null) {
            String fmtDateStr = sdf.format(value);
            gen.writeString(fmtDateStr);
        }
    }

}

DateJsonDeserializer

写一个Date类型的反序列化器

@Slf4j
public class DateJsonDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String valueStr = p.getValueAsString();
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(valueStr);
        } catch (ParseException e) {
            log.error("解析时间错误");
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ObjectMapper是一个非常流行的Java库,用于将Java对象转换为JSON格式,以及将JSON格式转换为Java对象。下面是一个使用ObjectMapper的示例代码: ``` import com.fasterxml.jackson.databind.ObjectMapper; public class Example { public static void main(String[] args) { // Create an instance of ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Convert a Java object to JSON MyObject myObject = new MyObject("John", 30); try { String json = objectMapper.writeValueAsString(myObject); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } // Convert JSON to a Java object String json = "{\"name\":\"John\",\"age\":30}"; try { MyObject myObject = objectMapper.readValue(json, MyObject.class); System.out.println(myObject.getName()); System.out.println(myObject.getAge()); } catch (JsonProcessingException e) { e.printStackTrace(); } } } class MyObject { private String name; private int age; public MyObject() {} public MyObject(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; } } ``` 在上面的示例中,我们首先创建了一个ObjectMapper实例。然后,我们将一个Java对象转换为JSON字符串,使用writeValueAsString()方法。接着,我们将JSON字符串转换为Java对象,使用readValue()方法。注意,我们需要传入要转换的Java对象的类类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值