英文:
Parsing a value from json response where most of the payload is redundant
问题
从这个 JSON 载荷中提取 name
字段的方法:
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public String getPostsPlainJSON() {
String url = "https://restcountries.eu/rest/v2/name/eesti";
String response = this.restTemplate.getForObject(url, String.class);
// 使用 JSON 解析库来提取 name 字段,例如使用 Jackson、Gson 等
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(response);
String name = jsonElement.getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();
return name;
}
}
在上述示例中,我们首先通过 RestTemplate
获取 JSON 响应。然后,我们使用一个 JSON 解析库(比如 Jackson、Gson 等)来解析 JSON 并提取所需的 name
字段。通过解析 JSON 数组并获取第一个对象,我们可以得到 name
字段的值。这样就避免了创建一个新的 MyCustomObject
类来映射整个 JSON 响应,而只关注提取单独的字段。
英文:
To extract the name
field from this json payload:
[{"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"}]
I plan to use code similar to:
@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
will contain many redundant fields that I'm not concerned with as I just wish to access the name "Estonia"
for the above example. Is there an alternative method for parsing the field name
rather than creating a new MyCustomObject
pojo that maps to the entire JSON response?
答案1
得分: 2
你可以使用JSONPath
public static void main(String[] args) {
String json = "[{\"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\"}]";
String jsonPath = "$.[*].name";
DocumentContext jsonContext = JsonPath.parse(json);
List<String> result = jsonContext.read(jsonPath);
System.out.println("name :: " + result.get(0));
result = jsonContext.read("$.[*].capital"); // 获取首都
System.out.println("Capital :: " + result.get(0));
}
输出
name :: Estonia
Capital :: Tallinn
Maven 依赖
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
英文:
You can Use JSONPath
public static void main(String[] args) {
String json = "[{\"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\"}]";
String jsonPath = "$.[*].name";
DocumentContext jsonContext = JsonPath.parse(json);
List<String> result = jsonContext.read(jsonPath);
System.out.println("name :: "+result.get(0));
result = jsonContext.read("$.[*].capital"); //To get Captial
System.out.println("Capital :: "+result.get(0));
}
output
name :: Estonia
Capital :: Tallinn
Maven dependency
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论