我使用restTemplate从第三方API获取详细信息。
其中,下面的代码给我一个字符串的响应(使用response.getBody())
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
JSON示例
{"Entries":[{"EntryId":"1","Field1":"1","Field2":"2"},{"EntryId":"2","Field1":"3","Field2":"4"}]}
我还创建了一个名为Entries的类,
@JsonIgnoreProperties(ignoreUnknown=true)
public class Entries {
@JsonProperty("EntryId")
private String entryId;
@JsonProperty("Field1")
private String field1;
@JsonProperty("Field2")
private String field2;
//getter and setters
有没有办法使用RestTemplate将JSON数组映射到Entires类?
答案 0 :(得分:0)
有两种方法,
[1]使用ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Entries obj = mapper.readValue(rrateResponse.getBody(), Entries.class);
[2]传递条目类
ResponseEntity<Entries> result = restTemplate.exchange(uri, HttpMethod.GET, entity, Entries.class);
唯一缺少的是下面提到的参赛作品。
@JsonIgnoreProperties(ignoreUnknown=true)
public class Entries {
@JsonProperty("Entries")
private List<Entry> Entries;
//getter and setter