0

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

3
  • Can you try something like this? ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy")); Commented Jun 6, 2020 at 15:13
  • I tried your suggestion - It's not working @Govind Commented Jun 8, 2020 at 6:56
  • Getting Error: Multiple Failures (2 failures) com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('31-12-2019') Commented Jun 8, 2020 at 7:25

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Ashish - I tried your suggestion. I'm getting a error com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('31-12-2019')
@Debugger check JSON date format and POJO date format. it seems like you are validating with different date format.
1

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

3 Comments

Thanks - I tried your suggestion -I'm getting a error com.fasterxml.jackson.databind.JsonMappingException: Text '31-12-2019' could not be parsed at index 0 (through reference chain: com.bre.fact.model.CautionFact["matchDate"])- Can you pls advise @lucid
I'm using @SpringBootTest, because for Unit testing
@Debugger can you add little bit of Main.class just class level annotation ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.