[英]JSON response customize the response content
我已经实现了Spring MVC 3代码来获取JSON响应(借助Jackson映射器)
@RequestMapping(value = "/getallroles", method = RequestMethod.GET)
@ResponseBody
public JsonJtableResponse1 getAllRoles(){
List<Role> roleList = testService.getAllRoles();
JsonJtableResponse1 jstr = new JsonJtableResponse1("OK",roleList);
return jstr;
}
JSON响应对象就是这样。
public class JsonJtableResponse1 {
private String Result;
private List<Role> Records;
public JsonJtableResponse1(String Result) {
this.Result = Result;
}
public JsonJtableResponse1(List<Role> Records) {
this.Records = Records;
}
public JsonJtableResponse1(String Result, List<Role> Records) {
this.Result = Result;
this.Records = Records;
}
public String getResult() {
return Result;
}
public void setResult(String Result) {
this.Result = Result;
}
public List<Role> getRecords() {
return Records;
}
public void setRecords(List<Role> Records) {
this.Records = Records;
}
}
从spring方法getAllRoles()返回的JSON是
{"result":"OK","records":[
{"custId":"1","name":"aaa","birthYear":"1982","employer":"XX","infoAsOfDate":"20130110","disabled":"true"},
{"custId":"2","name":"bbb","birthYear":"1982","employer":"YY","infoAsOfDate":"20130111","disabled":"true"},
{"custId":"3","name":"ccc","birthYear":"1982","employer":"XX","infoAsOfDate":"20130108","disabled":"false"},
{"custId":"4","name":"ddd","birthYear":"1981","employer":"TT","infoAsOfDate":"20130107","disabled":"true"}
]}
我需要JSON作为-[两个元素中都注意大写R]
{"Result":"OK","Records":[ ....................
..............................................
]}
使用Jakson映射器创建JSON响应时要考虑到对象的getter / setter名称。如何获得所需的JSON响应格式?
您可以使用注释@JsonProperty
自定义名称:
@JsonProperty("Result")
public String getResult() {
return Result;
}
如果您需要所有属性名称都将首字母大写,则可以通过扩展PropertyNamingStrategy
来更改默认命名约定。 例如,您可以阅读此博客文章http://www.cowtowncoder.com/blog/archives/2011/03/entry_448.html 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.