1

I want to know what is the rule followed by MappingJackson2HttpMessageConverter to convert the object (returned from controller method annotated by @ResponseBody) to a json? In some situations I see that just having Jackson2 on classpath (pom.xml) is enough and the controller simply returns back its object e.g. String or a collection e.g. List<Employee> successfully to browser in json format. But, in other cases I have seen that the solution asks me to use an ObjectMapper and use method writeValueAsString to get a string and return that as a response, example HashMaps! Are there some implicit rules which MappingJackson2HttpMessageConverter uses to decide if it is able to do the conversion on its own or I need to manually do it using Objectmapper ? If I have a pojo object, which internally has few String fields, would I still need to use ObjectMapper etc? If not then would I need it if my pojo class has fields like , some List<CustomObject> and some HashMaps? For example : example 1 does not use any ObjectMapper to convert List<Company> to json in controller method. But, example 2 needs an ObjectMapper and writeValueAsString ? plus, it's return type now is String instead of a HashMap!

Community
  • 1
  • 1
Kumar Manish
  • 1,166
  • 1
  • 16
  • 28

1 Answers1

0

If you use @RestController and you have jackson in the class path everything will be handled OK. see https://spring.io/guides/gs/rest-service/ and https://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/

Essex Boy
  • 7,565
  • 2
  • 21
  • 24
  • So it would work for any kind of return type ? Complex POJO object with Strings/Lists/Maps? And no need to use `ObjectMapper` ? So when would I need to use an `ObjectMapper` in a controller method? p.s. This link also corroborates what you said, though: http://stackoverflow.com/questions/10284025/spring-mvc-is-it-possible-to-return-a-mapstring-object-dynamically-converted – Kumar Manish Mar 29 '17 at 13:57
  • Very very rarely will you have to do anything, Jackson and @RestController is all you need. – Essex Boy Mar 29 '17 at 14:13
  • So what could be a use case of using `ObjectMapper` & 'writeValueAsString' in a `@Controller` ? – Kumar Manish Mar 29 '17 at 16:21
  • If in the very rare case that Jackson can't handle the de-serialization, then you should define a JsonDeserializer (see http://stackoverflow.com/questions/35724693/jackson-deserialize-object-with-list-of-springs-interface/35726158#35726158) and assign it to the POJO, you never do it in the Controller. The Controller should return a ResponseEntity. – Essex Boy Mar 30 '17 at 06:58