Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate with Jackson as HttpMessageConverter and joda DateTime property fails to deserialize

The scenario is as follows. I have an ObjectMapper (Jackson 2) that registers a JodaModule, capable of serializing and de-serializing Joda DateTime type. This ObjectMapper is tested with custom JSON strings and works as expected.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
objectMapper.setDateFormat(new ISO8601DateFormat());
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;

I have an RestTemplateFactory which is responsible for instantiating a RestTemplate, and it sets the previously configured ObjectMapper bean to the RestTemplate.

@Configuration
public class RestTemplateFactory {

  @Autowired
  private ObjectMapper objectMapper;

  @Bean
  public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonMessageConverter.setObjectMapper(objectMapper);
    messageConverters.add(jsonMessageConverter);
    // restTemplate.setMessageConverters(messageConverters); // This line was missing, but needs to be here. See answer.
    return restTemplate;
  }
}

Now when I contact the webservice it fails to de-serialize the DateTime object with the following error message:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not instantiate value of type [simple type, class org.joda.time.DateTime] from String value; no single-String constructor/factory method

Also the DateTimeDeserializer.class is never called. Anyone has an idea what I am missing here?

like image 875
Spase Markovski Avatar asked Jan 25 '14 19:01

Spase Markovski


2 Answers

OK, I was missing this line in my createRestTemplate() method.

restTemplate.setMessageConverters(messageConverters);
like image 83
Spase Markovski Avatar answered Oct 01 '22 08:10

Spase Markovski


Add dependency

      <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.9.0.pr4</version>
    </dependency>

and use DateTimeDeserializer.class for deserializing as below

@JsonDeserialize(using = DateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy", timezone = "Europe/Berlin")
private DateTime date;

works fine for me. No need to add a custom message convertor.

like image 31
Rohit Naik Avatar answered Oct 01 '22 09:10

Rohit Naik