简体   繁体   中英

JSON response customize the response content

I have implemented a spring mvc 3 code to obtain JSON response (with help of 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;
}

The JSON response object is like this.

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

returned JSON from spring method getAllRoles() is

{"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"}
]}

I need JSON as - [NOTE UPPER CASE R in both elements]

{"Result":"OK","Records":[ ....................
 ..............................................
]}

with Jakson mapper the JSON response is created taking in to account the getter/setter names of the object .How can I achieve the required format of JSON response?

You can customized names using the annotation @JsonProperty :

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

If you need to have all your properties names to have the first letter to be in upper case, you could change the default naming convention by extending the PropertyNamingStrategy . For example you can read this blog post http://www.cowtowncoder.com/blog/archives/2011/03/entry_448.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM