亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Java 訪問嵌套 JSON 對象的最佳方法

使用 Java 訪問嵌套 JSON 對象的最佳方法

一只名叫tom的貓 2023-08-09 17:01:31
我是使用 JSON 的新手,我想知道是否有更好的方法來完成我在下面的代碼中所做的事情。您會注意到,要訪問嵌套的 JSON 對象,我必須先創建子 JSON 對象/數組,然后才能訪問 JSON 數組元素&ldquo;leagues&rdquo;。有沒有更快或更簡單的方法來做到這一點?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") + " " );? ? }}
查看完整描述

1 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

您可以使用Gson或JacksonJSON將有效負載反序列化為類。此外,這兩個庫還可以反序列化to?-?to和to?、或任何其他集合。使用jsonschema2pojo?,您可以為已經帶有注釋的給定負載生成類。POJOJSONJava CollectionJSON ObjectsMapJSON ArrayListSetarray (T[])POJOJSONGsonJackson

當您不需要處理整個JSON有效負載時,您可以使用JsonPath庫對其進行預處理。例如,如果您只想返回聯賽名稱,則可以使用$..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 + '\'' +

? ? ? ? ? ? ? ? '}';

? ? }

}

上面的代碼打印:


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'}


查看完整回答
反對 回復 2023-08-09
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號