1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用Gson或JacksonJSON
將有效負(fù)載反序列化為類。此外,這兩個(gè)庫(kù)還可以反序列化to?-?to和to?、或任何其他集合。使用jsonschema2pojo?,您可以為已經(jīng)帶有注釋的給定負(fù)載生成類。POJO
JSON
Java Collection
JSON Objects
Map
JSON Array
List
Set
array (T[])
POJO
JSON
Gson
Jackson
當(dāng)您不需要處理整個(gè)JSON
有效負(fù)載時(shí),您可以使用JsonPath庫(kù)對(duì)其進(jìn)行預(yù)處理。例如,如果您只想返回聯(lián)賽名稱,則可以使用$..leagues[*].name
路徑。您可以使用在線工具進(jìn)行嘗試并提供您的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'}
添加回答
舉報(bào)