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
java.time.LocalDate(no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('31-12-2019')