讓jackson支持jdk8的日期類型LocalDate

jackson-databind包默認不支持jdk8新的日期類型LocalDate。該問題處理方式以下:java

  • 添加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>
  • 代碼例子
package com.fasterxml.jackson;

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 org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.time.LocalDate;


public class JacksonTest {

    @Test
    public void test() throws IOException {

        ClassA a = new ClassA();
        a.setName("name1");
        a.setLocalDate(LocalDate.now());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());

        String json = mapper.writeValueAsString(a);
        System.out.println(json);

        ClassA a2 = mapper.readValue(json, ClassA.class);
        Assert.assertEquals(a.getName(), a2.getName());
        Assert.assertEquals(a.getLocalDate(), a2.getLocalDate());

    }

    static class ClassA {

        private String name;

        @JsonFormat(pattern = "yyyy-MM-dd")
        private LocalDate localDate;

        public LocalDate getLocalDate() {
            return localDate;
        }

        public void setLocalDate(LocalDate localDate) {
            this.localDate = localDate;
        }

        public String getName() {
            return name;
        }

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

    }

}
  • 參考
  1. https://github.com/FasterXML/jackson-modules-java8
  2. http://stackoverflow.com/questions/31896650/serialization-of-java-8-zoneddatetime-with-jackson-and-javatimemodule
  3. http://stackoverflow.com/questions/27952472/serialize-deserialize-java-8-java-time-with-jackson-json-mapper
相關文章
相關標籤/搜索