Jackson处理Java8LocalDateTime类的序列化问题

Jackson介绍

Jackson作为一个知名,并且经典的Java平台的JSON库,有人说它是最好的JSON解析工具,或者只是一个简单的还行的JSON解析库,不管如何Jackson都是一个值得一学,值得一用的JSON处理库。

背景

有一个实体类,里面有个字段

private LocalDateTime createdTime;

将该字段序列化为Json格式时会有一大堆的字符,我想要的是指定的格式(yyyy-MM-dd HH:mm:ss)并且需要在转换的时候加上时区(加8小时)

解决方案一

maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
    <version>2.8.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
    <version>2.8.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.8.8</version>
</dependency>

测试代码

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 测试jackson对LocalDateTime序列化
 */
public class TestJacksonLocalDateTime {

    /**
     * 实体类
     */
    static class MyDate {
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        private LocalDateTime createdTime;

        public LocalDateTime getCreatedTime() {
            return createdTime;
        }

        public void setCreatedTime(LocalDateTime createdTime) {
            this.createdTime = createdTime;
        }

        @Override
        public String toString() {
            return "MyDate{" +
                    "createdTime=" + createdTime +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        MyDate myDate = new MyDate();
        myDate.setCreatedTime(LocalDateTime.now());
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        String res = mapper.writeValueAsString(myDate);
        // 打印序列化后的数据:{"createdTime":"2020-01-21 17:36:27"}
        System.out.println(res);
        MyDate myDate1 = mapper.readValue(res, MyDate.class);
        // 打印反序列化后的数据:MyDate{createdTime=2020-01-21T17:36:27}
        System.out.println(myDate1);
    }

}

解决方案二

依赖同上

在LocalDateTime类型的字段上加上注解

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime createdTime;

你可能感兴趣的:(Java,jackson,json)