JSON响应自定义响应内容

时间:2013-01-15 23:23:41

标签: json spring spring-mvc jackson

我已经实现了一个spring mvc 3代码来获取JSON响应(在jackson mapper的帮助下)

@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方法返回JSON getAllRoles()是

{"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 mapper创建JSON响应,考虑对象的getter / setter名称。如何实现所需的JSON响应格式?

1 个答案:

答案 0 :(得分:2)

您可以使用注释@JsonProperty自定义名称:

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

如果您需要拥有所有属性名称以使第一个字母为大写,则可以通过扩展PropertyNamingStrategy来更改默认命名约定。例如,您可以阅读此博文http://www.cowtowncoder.com/blog/archives/2011/03/entry_448.html