答案取决于您的用例。我的建议是您创建一个完全符合您需求的自定义值对象,将其返回,然后让 Jackson 为您处理序列化:
@ResponseBody
@RequestMapping(value = "/someAjaxResponse", method = RequestMethod.POST)
public CustomValueObject someAjaxResponse(HttpServletRequest request, HttpServletResponse response) {
}
您所要做的就是将<mvc:annotation-driven />
or添加@EnableWebMvc
到您的应用程序上下文中,将 Jackson 依赖项添加到您的类路径中,然后该对象将自动序列化为 JSON,因为您使用了@ResponseBody
注释。
阅读MappingJacksonHttpMessageConverter
Spring 参考手册中的更多信息:
请注意,返回的对象可能具有复杂的结构。想象一下,您想向客户端提供人员数据,然后您可以Person
从控制器方法返回一个对象:
public class Person {
public String getFirstName() {...}
public int getAge() {...}
List<String> getEmailAddresses() {...}
Address getAddress() {...}
}
public class Address {
public String getStreet() {...}
public int getHouseNumber() {...}
public String getCity() {...}
public int getZIP() {...}
public String getState() {...}
}
可以序列化为:
{
"firstName": "John",
"lastName": "Doe",
"age": 42,
"emailAddresses": [
"john@doe.com",
"john.doe@somewhere.com"
],
"address": {
"street": "First Avenue",
"houseNumber": 123,
"city": "Smallville",
"ZIP": 12345,
"state": "CA"
}
}