用Java访问嵌套JSON对象的最佳方法 [英] Best way to access nested JSON objects with Java
问题描述
我是使用JSON的新手,我想知道是否有更好的方法来完成下面代码中的工作.您将注意到访问嵌套的JSON对象后,我必须创建子JSON对象/数组,然后才能进入JSON数组元素联盟".有没有更快或更简单的方法来做到这一点?
I am new to working with JSON and I am wondering if there is a better way to accomplish what I am doing in the below code. You will notice to access a nested JSON object I am having to create child JSON Objects/Arrays before I can get to the JSON array element "leagues". Is there a faster or easier way to do this?
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") + " " );
}
}
推荐答案
您可以使用 Jackson .同样,这两个库可以将JSON
到Java Collection
-JSON Objects
到Map
和JSON Array
到List
,Set
,array (T[])
或任何其他集合反序列化.使用 jsonschema2pojo 您可以为已经具有Gson
或POJO
类>注释.
You can deserialise JSON
payload to POJO
classes using Gson or Jackson. Also, these two libraries can deserialise JSON
to Java Collection
- JSON Objects
to Map
and JSON Array
to List
, Set
, array (T[])
or any other collection. Using jsonschema2pojo you can generate POJO
classes for given JSON
payload already with Gson
or Jackson
annotations.
当您不需要处理整个JSON
负载时,可以使用 JsonPath对其进行预处理一个>库.例如,如果您只想返回联赛名称,则可以使用$..leagues[*].name
路径.您可以使用在线工具进行尝试,并提供您的JSON
和路径.
When you do not need to process the whole JSON
payload you can preprocess it using JsonPath library. For example, if you want to return only league names you can use $..leagues[*].name
path. You can try it out using online tool and provide your JSON
and path.
您可以使用Jackson
轻松解决您的问题,如下所示:
Your problem can be easily solved using Jackson
as below:
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对象一个元素的数组
- 使用杰克逊反序列化为自定义对象的HashMap
- 使用Jackson解析深度嵌套的JSON属性
- 从Java类创建JSON模式
- Gson对具有不同值类型的json反序列化
- 什么是简单的方法完全忽略带有Java URL连接的ssl?
- How to ignore enum fields in Jackson JSON-to-Object mapping?
- Make Jackson interpret single JSON object as array with one element
- Deserializing into a HashMap of custom objects with jackson
- Parsing deeply nested JSON properties with Jackson
- Create JSON schema from Java class
- Gson deserialize json with varying value types
- Whats an easy way to totally ignore ssl with java url connections?
这篇关于用Java访问嵌套JSON对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!