json 使用 resttemplate 解析
json parsing with 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 class(MyMessage) 来解析 "value"?
RestTemplate rest = new RestTemplate();
ResponseEntity<MyMessage> response = rest.exchange(url, HttpMethod.GET, entity, MyMessage.class);
有人可以帮忙吗?
使用 @JsonProperty
注释 bean 属性,以便为 属性 设置 JSON 字段名称(如果不同)。
参见:
JsonProperty annotation and When is the @JsonProperty property used and what is it used for?
示例(为了简单起见,bean 属性为 public):
我的消息class:
public class MyMessage {
@JsonProperty("@odata.context")
public String context;
@JsonProperty("value")
public Value[] values;
}
值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;
}
我有一个 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 class(MyMessage) 来解析 "value"?
RestTemplate rest = new RestTemplate();
ResponseEntity<MyMessage> response = rest.exchange(url, HttpMethod.GET, entity, MyMessage.class);
有人可以帮忙吗?
使用 @JsonProperty
注释 bean 属性,以便为 属性 设置 JSON 字段名称(如果不同)。
参见:
JsonProperty annotation and When is the @JsonProperty property used and what is it used for?
示例(为了简单起见,bean 属性为 public):
我的消息class:
public class MyMessage {
@JsonProperty("@odata.context")
public String context;
@JsonProperty("value")
public Value[] values;
}
值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;
}