【问题标题】:Best way to access nested JSON objects with Java使用 Java 访问嵌套 JSON 对象的最佳方式
【发布时间】:2020-01-19 16:50:42
【问题描述】:

我是使用 JSON 的新手,我想知道是否有更好的方法来完成我在下面的代码中所做的事情。您会注意到要访问嵌套的 JSON 对象,我必须先创建子 JSON 对象/数组,然后才能访问 JSON 数组元素“leagues”。有没有更快或更简单的方法来做到这一点?

public static void main( String[] args ) throws UnirestException
{
    JsonNode response = Unirest.get("http://www.api-football.com/demo/api/v2/leagues")
            .header("x-rapidapi-host", "api-football-v1.p.rapidapi.com")
            .header("x-rapidapi-key", "")
            .asJson()
            .getBody();

    JSONObject json = new JSONObject( response );
    JSONArray jArray = json.getJSONArray( "array" );
    JSONObject jAPI = jArray.getJSONObject(0);
    JSONObject jLeagues = jAPI.getJSONObject( "api" );
    JSONArray jArrayLeagues = jLeagues.getJSONArray( "leagues" );

    for(int n = 0; n < jArrayLeagues.length(); n++) {
        JSONObject leagues = jArrayLeagues.getJSONObject(n);
        System.out.print(leagues.getString("name") + " " );
        System.out.print(leagues.getString("country") + " ");
        System.out.println( leagues.getInt("league_id") + " " );
    }
}

Link to the JSON data

【问题讨论】:

  • gson 或杰克逊怎么样?
  • 不能说我对任何一个都了解很多,但我会研究这两个。谢谢!
  • 我个人使用 gson 是因为它的易用性和高度可定制性。

标签: java json


【解决方案1】:

您可以使用GsonJacksonJSON 有效负载反序列化为POJO 类。此外,这两个库可以将JSON 反序列化为Java Collection - JSON ObjectsMapJSON ArrayListSetarray (T[]) 或任何其他集合。使用jsonschema2pojo,您可以使用GsonJackson 注释为给定的JSON 有效负载生成POJO 类。

当您不需要处理整个JSON 有效负载时,您可以使用JsonPath 库对其进行预处理。例如,如果您只想返回联赛名称,您可以使用$..leagues[*].name 路径。您可以使用online tool 进行尝试,并提供您的JSON 和路径。

使用Jackson 可以轻松解决您的问题,如下所示:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonPointer;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URL;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        // workaround for SSL not related with a question
        SSLUtilities.trustAllHostnames();
        SSLUtilities.trustAllHttpsCertificates();

        String url = "https://www.api-football.com/demo/api/v2/leagues";

        ObjectMapper mapper = new ObjectMapper()
                // ignore JSON properties which are not mapped to POJO
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        // we do not want to build model for whole JSON payload
        JsonNode node = mapper.readTree(new URL(url));

        // go to leagues JSON Array
        JsonNode leaguesNode = node.at(JsonPointer.compile("/api/leagues"));

        // deserialise "leagues" JSON Array to List of POJO
        List<League> leagues = mapper.convertValue(leaguesNode, new TypeReference<List<League>>(){});
        leagues.forEach(System.out::println);
    }
}

class League {
    @JsonProperty("league_id")
    private int id;
    private String name;
    private String country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "League{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", country='" + country + '\'' +
                '}';
    }
}

上面的代码打印:

League{id=2, name='Premier League', country='England'}
League{id=6, name='Serie A', country='Brazil'}
League{id=10, name='Eredivisie', country='Netherlands'}
League{id=132, name='Champions League', country='World'}

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多