如何使用Java访问JSON中的嵌套元素(Bing-Search-API) [英] How to access nested elements from a JSON using Java (Bing-Search-API)

查看:146
本文介绍了如何使用Java访问JSON中的嵌套元素(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 可以找出要填充的对象的类别。

  • 属性/字段的命名不一致,有些以小写开头,其他以大写字母开头。确保它们在java类和json字符串中相同(考虑区分大小写)。这个问题可以通过使用适当的 FieldNamingStrategy 用于序列化/反序列化。


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

这篇关于如何使用Java访问JSON中的嵌套元素(Bing-Search-API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆