问题
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