1 回答
TA贡献1802条经验 获得超4个赞
您可以使用Gson或JacksonJSON
将有效负载反序列化为类。此外,这两个库还可以反序列化to - to和to 、或任何其他集合。使用jsonschema2pojo ,您可以为已经带有注释的给定负载生成类。POJO
JSON
Java Collection
JSON Objects
Map
JSON Array
List
Set
array (T[])
POJO
JSON
Gson
Jackson
当您不需要处理整个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'}
添加回答
举报