用Java访问嵌套JSON对象的最佳方法

时间:2019-09-18 17:04:53

标签: java json

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用GsonJacksonJSON有效负载反序列化为POJO类。此外,这两个库可以将JSONJava Collection-JSON ObjectsMap以及JSON ArrayListSet,{ {1}}或任何其他集合。使用jsonschema2pojo,您可以为已经带有array (T[])POJO批注的给定JSON有效负载生成Gson类。

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

使用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 + '\'' +
                '}';
    }
}

另请参阅: