您可以反序列化JSON
有效负载到POJO
类使用Gson or Jackson。另外,这两个库可以反序列化JSON
to Java Collection
- JSON Objects
to Map
and JSON Array
to List
, Set
, array (T[])
或任何其他集合。使用jsonschema2pojo你可以生成POJO
给定的类JSON
有效负载已经Gson
or 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'}
也可以看看:
- 如何忽略 Jackson JSON 到对象映射中的枚举字段?
- 让 Jackson 将单个 JSON 对象解释为包含一个元素的数组
- 使用 Jackson 反序列化为自定义对象的 HashMap
- 使用 Jackson 解析深度嵌套的 JSON 属性
- 从 Java 类创建 JSON 模式
- Gson 反序列化具有不同值类型的 json
- 有什么简单的方法可以完全忽略带有 java url 连接的 ssl ?