3 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
試試下面的代碼。您不能直接訪問國家/地區(qū),它是放置在嵌套對(duì)象中的值。而且由于響應(yīng)主體作為數(shù)據(jù)返回,因此您無法將其轉(zhuǎn)換為用戶對(duì)象。首先,您需要將其轉(zhuǎn)換為數(shù)據(jù)對(duì)象。
public class User {
private int id;
private String name;
private String urlPicture;
private Address address;
// getters and setters
}
public class Address {
private String country;
// getters and setters
}
public void testResponse(){
RestTemplate restTemplate = new RestTemplate();
Data data = new Data();
User user = new User();
Gson gson = new Gson();
String response = restTemplate.getForObject(
"https://apifrommyrequest.com/user/{id}",
String.class,
73442);
data = gson.fromJson(response, Data.class);
System.out.println(data);
}

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果你愿意,你也可以像這樣設(shè)計(jì)你的 POJO(以減少嵌套的 POJO):
public class Data {
private User data;
//getters and setters
}
public class User {
private int id;
private String name;
private String urlPicture;
private String country;
@JsonProperty("address")
private void unpackNested(Map<String,String> elements)
{
this.country = elements.get("country");
}
//getters and setters
}
然后最后在 Data 類上反序列化

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
你真的不需要做從字符串到對(duì)象的轉(zhuǎn)換,resttemplate 已經(jīng)使用 jackson 為你做了,只需要
YourObject response = restTemplate.getForObject(
"https://apifrommyrequest.com/user/{id}",
YourObject.class,
73442);
然后它將映射到你的 pojo 對(duì)象,在這種情況下你真的不需要 gson。
添加回答
舉報(bào)