How to access nested elements from a JSON using Java (Bing-Search-API)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 13:44:27

问题


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 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.


来源:https://stackoverflow.com/questions/18214447/how-to-access-nested-elements-from-a-json-using-java-bing-search-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!