我转换为控制器以使用 ContentNegotiatingViewResolver 而不是 MessageConverters 来支持多种输出类型。使用 json,我正在使用 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 类似于:
{
myObject: {
field1:"abc",
field2:"efg"
}
}
有没有办法让我将 myObject 设置为结果的顶级节点,所以它看起来像这样:
{
field1:"abc",
field2:"efg"
}