2013-01-15 36 views
0

我已經實現的彈簧MVC 3代碼以獲得JSON響應(傑克遜映射器的幫助下)JSON響應定製響應內容

@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; 
    } 
} 

從彈簧方法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響應格式?

回答

2

您可以使用註釋@JsonProperty自定義名稱:

@JsonProperty("Result") 
public String getResult() { 
    return Result; 
} 

如果你需要讓你的所有屬性名稱有首字母大寫,你可以更改默認通過擴展命名約定PropertyNamingStrategy。例如,你可以閱讀這篇博文http://www.cowtowncoder.com/blog/archives/2011/03/entry_448.html