json parsing with resttemplate

时光总嘲笑我的痴心妄想 提交于 2019-12-13 02:33:54

问题


I have a json response as below

{
    "@odata.context": "some context value here",
    "value": [{
        "@odata.id": "odata id value1",
        "@odata.etag": "W/\"CQEet/1EgOuA\"",
        "Id": "id1",
        "Subject": "subject1"
    }, {
        "@odata.id": "odata id value2",
        "@odata.etag": "W/\"CyEet/1EgOEk1t/\"",
        "Id": "id2",
        "Subject": "subject2"
    }]
}

How do I create a bean class(MyMessage) to parse the "value" using spring resttemplate?

RestTemplate rest = new RestTemplate();
ResponseEntity<MyMessage> response = rest.exchange(url, HttpMethod.GET, entity, MyMessage.class);

Could someone please help?


回答1:


Annotate bean properties with @JsonProperty to set JSON field name for the property if it is different.

See:

JsonProperty annotation and When is the @JsonProperty property used and what is it used for?

Example (bean properties are public for example simplicity):

MyMessage class:

public class MyMessage {

    @JsonProperty("@odata.context")
    public String context;

    @JsonProperty("value")
    public Value[] values;
}

Value class:

// PascalCaseStrategy is to resolve Id and Subject properties
@JsonNaming(PascalCaseStrategy.class)
public class Value {

    @JsonProperty("@odata.id")
    public String odataId;

    @JsonProperty("@odata.etag")
    public String odataEtag;

    public String id;
    public String subject;
}


来源:https://stackoverflow.com/questions/37097199/json-parsing-with-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!