【发布时间】:2020-09-14 21:33:48
【问题描述】:
要从此 json 有效负载中提取 name 字段:
[{"name":"Estonia","topLevelDomain":[".ee"],"alpha2Code":"EE","alpha3Code":"EST","callingCodes":["372"],"capital":"Tallinn","altSpellings":["EE","Eesti","Republic of Estonia","Eesti Vabariik"],"region":"Europe","subregion":"Northern Europe","population":1315944,"latlng":[59.0,26.0],"demonym":"Estonian","area":45227.0,"gini":36.0,"timezones":["UTC+02:00"],"borders":["LVA","RUS"],"nativeName":"Eesti","numericCode":"233","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"et","iso639_2":"est","name":"Estonian","nativeName":"eesti"}],"translations":{"de":"Estland","es":"Estonia","fr":"Estonie","ja":"エストニア","it":"Estonia","br":"Estônia","pt":"Estónia","nl":"Estland","hr":"Estonija","fa":"استونی"},"flag":"https://restcountries.eu/data/est.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"EST"}]
我打算使用类似的代码:
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public String getPostsPlainJSON() {
String url = "hhttps://restcountries.eu/rest/v2/name/eesti";
return this.restTemplate.getForObject(url, MyCustomObject.class);
}
}
MyCustomObject 将包含许多我不关心的冗余字段,因为我只想访问上面示例的名称 "Estonia"。是否有另一种方法来解析字段name,而不是创建一个映射到整个 JSON 响应的新 MyCustomObject pojo?
【问题讨论】:
标签: java json spring spring-boot