json用resttemplate解析

时间:2016-05-08 07:07:50

标签: java json spring resttemplate

我有一个json响应如下

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

如何使用spring resttemplate创建一个bean类(MyMessage)来解析“value”?

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

使用@JsonProperty注释bean属性,以便为属性设置JSON字段名称(如果不同)。

请参阅:

JsonProperty annotationWhen is the @JsonProperty property used and what is it used for?

示例(bean属性是公共的,例如简单性):

MyMessage类:

public class MyMessage {

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

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

价值等级:

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