MappingJacksonJsonView返回顶级json对象 [英] MappingJacksonJsonView return top-level json object
问题描述
我转换为控制器以使用ContentNegotiatingViewResolver而不是MessageConverters来支持多种输出类型。使用json,我使用MappingJacksonJsonView:
I converted to controller to use ContentNegotiatingViewResolver instead of MessageConverters to support multiple output types. With json, I am using MappingJacksonJsonView:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="application/json" />
</bean>
使用以下控制器逻辑:
@RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
public ModelAndView getById(@PathVariable (value="id") String id) {
MyObject ret = doGetById(id);
ModelAndView modelAndView = new ModelAndView("common/single");
modelAndView.addObject("myObject", ret);
return modelAndView;
}
当我访问/id/1234.json时,json返回如下:
The json return when I access /id/1234.json is something like:
{
myObject: {
field1:"abc",
field2:"efg"
}
}
我有办法将myObject设置为相反的顶级节点,所以它看起来像这样:
Is there a way for my to set myObject as the top level node for the result so it look like this instead:
{
field1:"abc",
field2:"efg"
}
推荐答案
正在发生的事情是Spring MVC正在使用ModelAndView并将其序列化为JSON。由于ModelAndView看起来像地图,在这种情况下,地图中只有一个条目,其名称为myObject,这就是JSON响应所看到的内容。为了获得你的对象,你需要只返回你的对象而不是ModelAndView,让Jackson将你的对象序列化为JSON。
What's happening is Spring MVC is taking the ModelAndView and serializing it to JSON. Since a ModelAndView just looks like a map, and in this case, you only have one entry in the map with a key name of myObject, that's what the JSON response looks at. In order to get just your object, you need to return just your object instead of a ModelAndView and let Jackson serialize your object to JSON.
而不是返回一个ModelAndView,返回一个MyObject并使用 @ResponseBody
注释该方法,因此您的控制器方法变为
Rather than returning a ModelAndView, return a MyObject and annotate the method with @ResponseBody
, so your controller method becomes
@RequestMapping(value="/id/{id}", method=RequestMethod.GET, produces="application/json")
public @ResponeBody MyObject getById(@PathVariable (value="id") String id) {
return doGetById(id);
}
这篇关于MappingJacksonJsonView返回顶级json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!