问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/18214447/how-to-access-nested-elements-from-a-json-using-java-bing-search-api