[英]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.