从JSON响应中解析一个值,其中大部分有效负载都是冗余的。

huangapple go评论71阅读模式
英文:

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 = &quot;[{\&quot;name\&quot;:\&quot;Estonia\&quot;,\&quot;topLevelDomain\&quot;:[\&quot;.ee\&quot;],\&quot;alpha2Code\&quot;:\&quot;EE\&quot;,\&quot;alpha3Code\&quot;:\&quot;EST\&quot;,\&quot;callingCodes\&quot;:[\&quot;372\&quot;],\&quot;capital\&quot;:\&quot;Tallinn\&quot;,\&quot;altSpellings\&quot;:[\&quot;EE\&quot;,\&quot;Eesti\&quot;,\&quot;Republic of Estonia\&quot;,\&quot;Eesti Vabariik\&quot;],\&quot;region\&quot;:\&quot;Europe\&quot;,\&quot;subregion\&quot;:\&quot;Northern Europe\&quot;,\&quot;population\&quot;:1315944,\&quot;latlng\&quot;:[59.0,26.0],\&quot;demonym\&quot;:\&quot;Estonian\&quot;,\&quot;area\&quot;:45227.0,\&quot;gini\&quot;:36.0,\&quot;timezones\&quot;:[\&quot;UTC+02:00\&quot;],\&quot;borders\&quot;:[\&quot;LVA\&quot;,\&quot;RUS\&quot;],\&quot;nativeName\&quot;:\&quot;Eesti\&quot;,\&quot;numericCode\&quot;:\&quot;233\&quot;,\&quot;currencies\&quot;:[{\&quot;code\&quot;:\&quot;EUR\&quot;,\&quot;name\&quot;:\&quot;Euro\&quot;,\&quot;symbol\&quot;:\&quot;€\&quot;}],\&quot;languages\&quot;:[{\&quot;iso639_1\&quot;:\&quot;et\&quot;,\&quot;iso639_2\&quot;:\&quot;est\&quot;,\&quot;name\&quot;:\&quot;Estonian\&quot;,\&quot;nativeName\&quot;:\&quot;eesti\&quot;}],\&quot;translations\&quot;:{\&quot;de\&quot;:\&quot;Estland\&quot;,\&quot;es\&quot;:\&quot;Estonia\&quot;,\&quot;fr\&quot;:\&quot;Estonie\&quot;,\&quot;ja\&quot;:\&quot;エストニア\&quot;,\&quot;it\&quot;:\&quot;Estonia\&quot;,\&quot;br\&quot;:\&quot;Est&#244;nia\&quot;,\&quot;pt\&quot;:\&quot;Est&#243;nia\&quot;,\&quot;nl\&quot;:\&quot;Estland\&quot;,\&quot;hr\&quot;:\&quot;Estonija\&quot;,\&quot;fa\&quot;:\&quot;استونی\&quot;},\&quot;flag\&quot;:\&quot;https://restcountries.eu/data/est.svg\&quot;,\&quot;regionalBlocs\&quot;:[{\&quot;acronym\&quot;:\&quot;EU\&quot;,\&quot;name\&quot;:\&quot;European Union\&quot;,\&quot;otherAcronyms\&quot;:[],\&quot;otherNames\&quot;:[]}],\&quot;cioc\&quot;:\&quot;EST\&quot;}]&quot;;
	
	String jsonPath = &quot;$.[*].name&quot;;  
    DocumentContext jsonContext = JsonPath.parse(json);
    List&lt;String&gt; result = jsonContext.read(jsonPath);
    System.out.println(&quot;name :: &quot;+result.get(0));
    
    result = jsonContext.read(&quot;$.[*].capital&quot;); //To get Captial
    System.out.println(&quot;Capital :: &quot;+result.get(0));	
}

output

name :: Estonia
Capital :: Tallinn

Maven dependency

&lt;dependency&gt;
    &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
    &lt;artifactId&gt;json-path&lt;/artifactId&gt;
    &lt;version&gt;2.4.0&lt;/version&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2020年9月15日 05:33:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63892105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定