如何使用Java访问JSON中的嵌套元素(Bing-Search-API) [英] How to access nested elements from a JSON using Java (Bing-Search-API)
问题描述
我使用Bing-Search-API检索了这个 JSON。现在,我不知道如何使用GSON访问嵌套元素。我已经为JSON结构数据制作了源文件。
如果我这样做:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
它会抛出我不是 JsonArray
,所以如果我将它更改为 JsonObject
,我如何从 Results.java ?
谢谢
基于 Gson class:
Gson gson = new Gson();
响应响应= gson.fromJson(jsonText,Response.class);
结果firstResult = response.getD()。getResults()。get(0);
System.out.println(firstResult.getMediaUrl());
所以你不需要使用 JsonParser
直接。
您的java类必须稍微修改才能使用:
D.java
中的结果
字段的类型必须为列出< Results>
以便 Gson
可以找出要填充的对象的类别。
I have this JSON that I retrieved using Bing-Search-API. Now, I'm not sure how to access the nested elements using GSON. I already made the source files for the JSON Structure Data.
If I do this:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
It is going to throw me that is not a JsonArray
, so If I change it to JsonObject
, how can I retrieve the String MediaUrl
from Results.java?
Thank you
Based on the javadoc of Gson class:
Gson gson = new Gson();
Response response = gson.fromJson(jsonText, Response.class);
Results firstResult = response.getD().getResults().get(0);
System.out.println(firstResult.getMediaUrl());
So you don't need to use the JsonParser
directly.
Your java classes have to be modified a little bit for this to work:
- the type of
results
field inD.java
has to beList<Results>
so thatGson
can find out the class of objects to populate with. - the naming of attributes/fields is inconsistent, some starts with lower case, others with uppercase. Make sure they are the same in the java classes and in the json string (considering case sensitivity). This issue might be addressed with using the appropriate FieldNamingStrategy for serialization/deserialization.
这篇关于如何使用Java访问JSON中的嵌套元素(Bing-Search-API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!