我有一个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)来解析“值”?
RestTemplate rest = new RestTemplate();
ResponseEntity<MyMessage> response = rest.exchange(url, HttpMethod.GET, entity, MyMessage.class);
有人可以帮忙吗?
最佳答案
用@JsonProperty
注释bean属性,以设置属性的JSON字段名称(如果不同)。
看到:
JsonProperty annotation和When 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;
}