3

I'm using a 3rd party REST API which is returning 'NaN' in it's JSON response :( I can't change the response.

I'm using Spring MVC with RestTemplate and the built in Message Converters to deserialize the JSON to an Object.

I was wondering, if there is a smart way of setting the JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS property to allow for the NaN in the response.

Because I have other message converters which I do not need to configure myself I'm currently doing the following:

List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
for (HttpMessageConverter converter : converters) {
    if (converter instanceof MappingJacksonHttpMessageConverter) {
        ObjectMapper objectMapper = ((MappingJacksonHttpMessageConverter) converter).getObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
    }
}

This works but I don't like the fact that I'm a) iterating and b) doing the instanceof comparison just to set this property.

What would be a smarter/nicer way to do this?

C0deAttack
  • 24,419
  • 18
  • 73
  • 81
  • Try to create your own instance of this bean, which already will be configured. Please, see this question: http://stackoverflow.com/questions/10650196/how-to-configure-mappingjacksonhttpmessageconverter-while-using-spring-annotatio – Michał Ziober May 20 '13 at 16:09

1 Answers1

1

Here are your options:

  1. Instantiate and configure MappingJacksonHttpMessageConverter then set the message converters of your resttemplate to that instance. See RestTemplate.html#setMessageConverters(java.util.List). Note that this will remove all default message converters that are automatically instantiated when you instantiate a RestTemplate.
  2. Use @JsonDeserialize. See http://dev.sghill.net/2012/04/how-do-i-write-jackson-json-serializer.html
ramirezag
  • 554
  • 5
  • 9
  • Regarding 1. I have other converters that I don't want to lose, or have to create manually since there is nothing special about them. As for 2. Writing my own implementation just to be able to set a property is overkill. Thanks for replying though. – C0deAttack May 20 '13 at 23:13