Question

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

Was it helpful?

Solution

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 in D.java has to be List<Results> so that Gson 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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top