Unable to Deserialize - Jackson LocalDate/Time - JUnit

依然范特西╮ 提交于 2020-06-17 15:49:43

问题


I need to deserialize the Json to Java Objects in Junit. I have Json file like

{
   "studentId":57,
   "JoinedDate":"31-12-2019",
   "DOB":"08-06-1998"  

}

I have class for the same to map

public class Student{

    private long studentId ;

    private LocalDate JoinedDate;

    private LocalDate DOB ;

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public LocalDate getJoinedDate() {
        return JoinedDate;
    }

    public void setJoinedDate(LocalDate joinedDate) {
        JoinedDate = joinedDate;
    }

    public LocalDate getDOB() {
        return DOB;
    }

    public void setDOB(LocalDate dOB) {
        DOB = dOB;
    }

I need to write centralized builder for Unit testing project similar like this

builder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));

Main Class

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class Main{
    @Test
    public void contextLoads() {
        assertTrue(true);
    }

}

Unit testing Project looks like

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class StudentTest{

private ObjectMapper jsonObjectMapper;
@Before
public void setUp() throws IOException {

    jsonObjectMapper = new ObjectMapper();
    studentJson = IOUtils.toString(getClass().getResourceAsStream(CommonTestConstants.StudentPath+ "/Student.json"));


}

I'm getting a error while mapping the objects - com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDate from String "31-12-2019": Failed to deserialize java.time.LocalDate:

Another Error - Sometimes.

com.fasterxml.jackson.databind.JsonMappingException: Text '31-12-2019' could not be parsed at index 0

I assume LocalDate format mismatch is the issue. Any suggestion to make it centralized way instead of specifying the format above the fields. Any one please advise?

Reference - Spring Boot JacksonTester custom serializer not registered


回答1:


You just need to specify the date format by default jackson allows format of yyyy-MM-dd

public class Student{

    private long studentId ;

@JsonProperty("JoinedDate") @JsonFormat(pattern = "dd/MM/yyyy")

    private LocalDate JoinedDate;

@JsonProperty("DOB") @JsonFormat(pattern = "dd/MM/yyyy")
    private LocalDate DOB ;

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public LocalDate getJoinedDate() {
        return JoinedDate;
    }

    public void setJoinedDate(LocalDate joinedDate) {
        this.JoinedDate = joinedDate;
    }

    public LocalDate getDOB() {
        return DOB;
    }

    public void setDOB(LocalDate dOB) {
        this.DOB = dOB;
    }

I hope it helps you




回答2:


Springboot 1.4.x or above has this interface Jackson2ObjectMapperBuilderCustomizer which allows you to initialize objectMapper.

What we need to do, is override customize method and register deserializers and serializers.

@SpringBootApplication
public class TestApplication implements Jackson2ObjectMapperBuilderCustomizer {

  @Override
  public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
     // pattern could be anything whatever is required
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/dd/MM");

     LocalDateSerializer localDateDeserializer = new LocalDateSerializer(formatter);

     jackson2ObjectMapperBuilder
       .failOnEmptyBeans(false)
       .deserializersByType(new HashMap<Class<?>, JsonDeserializer<?>>(){{
         put(LocalTime.class, localTimeSerializer);
       }});
    }
}

We can also add seriliazers similar way.

jackson2ObjectMapperBuilder
   .failOnEmptyBeans(false)
   .serializersByType(new HashMap<Class<?>, JsonSerializer<?>>(){{
         put(LocalTime.class, localTimeSerializer);
   }});

you can check more details here. Spring Jackson builder



来源:https://stackoverflow.com/questions/62233024/unable-to-deserialize-jackson-localdate-time-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!