Reputation: 147
I have 2 microservices which communicate via REST call. I have an Entity named Consumer which has various fields including a LocalDate. When i pass this entity via REST call, i get the following exception
Json parse error expected array or string.,nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException
In Entity class,i annotated like below
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate dateOfBirth
In application.properties, i added the below line,
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
I am using Spring Boot version 2.1.2.RELEASE. In pom.xml, i have jackson dependencies.
I have added jackson-databind and jackson-datatype-jsr310,
both versions 2.9.9
I am using Retrofit as the client in 1st microservice through which i make the REST call to the REST ENDPOINT(@RestController) of the 2nd microservice.
But i get the error - Json Parse Error - MismatchedInputException for LocalDate. Is there anything more i need to add ?
EDIT-1 Following is the snippet of the generated JSON,
{"consumerId":1,"consumerName":"Harry","dateOfBirth":{"year":1991,"month":3,"day":10},"requestDate":"year":2020,"month":8,"day":31}
EDIT-2 I implemented following this link, http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/
Additionally added below as suggested by @rohit in the comments.
@JsonFormat(pattern="yyyy-MM-dd")
@JsonSerialize(using=LocalDateSerializer.class)
@JsonDeserialize(using=LocalDateDeserializer.class)
private LocalDate dateOfBirth
But still the date format generated in the JSON is not changing as per the format.
"dateOfBirth":{"year":1991,"month":3,"day":10}
It should be,
"dateOfBirth":"1991-03-10"
Isnt it ??
Is the bean defined in the SpringBoot main class not being used ?,
@Bean
@Primary
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
Now i am getting below error,
Json parse error: text; nested exception is com.fasterxml.jackson.databind.JsonMappingException: text (through reference chain com.model.Consumer["dateOfBirth"])
Upvotes: 4
Views: 5667
Reputation: 147
As i was using Retrofit,
Added a registerTypeAdapter to my GsonBuilder as below,
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
Upvotes: 1