In my ajax response, I want to return a JSON result.
I’m using spring mvc, and I have jackson in my pom.xml already.
Now in my controller’s action I have:
@ResponseBody
@RequestMapping(value = "/someAjaxResponse", method = RequestMethod.POST)
public String someAjaxResponse(HttpServletRequest request, HttpServletResponse response) {
}
What built in java datastructure/type do you suggest I use so I can then convert it to json using jackson?
I don’t want to create a new class for each response type, so I’m looking for a good general purpose java type for this purpose.
Suggestions?
For converting to json, which method would be best as I know jackson has multiple ways converting objects, like ObjectMapper which I believe you create a single instance of and re-use throughout the entire application? So does that mean I mark it as final?
The answer depends on your use case. My suggestion is that you create a custom value object that exactly fit your needs, return it and then let Jackson handle the serializaion for you:
All that you have to do is to add the
<mvc:annotation-driven />or@EnableWebMvcto your application context, add the Jackson dependencies to your classpath and then the object will be serialized to JSON automatically because you use the@ResponseBodyannotation.Read more about the
MappingJacksonHttpMessageConverterin the Spring reference manual:Note, the returned object can have complex structure. Imagine that you would like to provide person data to the client, then you can return a
Personobject from your controller method:Which may be serialized to: