Json使用Gson解析嵌套数组

时间:2016-03-01 17:35:46

标签: java json parsing gson

我还没有在网上看到一个(回答的)例子,它讨论了这种嵌套的json数组。

要解析的JSON:

{
    "Field": {
        "ObjectsList": [
            {
                "type": "Num",
                "priority": "Low",
                "size": 3.43
            },
            {
                "type": "Str",
                "priority": "Med",
                "size": 2.61
            }
        ]
    }
}

我为每个级别创建了一个班级'嵌套的json块。我希望能够解析" ObjectList"的内容。阵列。

任何人都可以帮我在Java中使用Gson解析这个JSON吗? 任何提示或代码片段都将不胜感激。

我的方法如下:

public static void main (String... args) throws Exception 
{
    URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
    try (InputStream input = jsonUrl.openStream(); 
         BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8"))) 
        {
         Gson gson = new GsonBuilder().create();
         ClassA classA = gson.fromJson(buffReader, ClassA.class);

         System.out.println(classA);
        }
    }
}


class ClassA 
{
    private String field;
    // getter & setter //
}

class ClassB
{
    private List<ClassC> objList;
    // getter & setter //
}

clas ClassC
{
    private String type;
    private String priority;
    private double size;
    // getters & setters //

    public String printStr()
    {
        return String.format(type, priority, size);
    }
}

2 个答案:

答案 0 :(得分:1)

以下代码段和源文件可以帮助您:

https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17

private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
  private JsonParser parser;

  public static void main(String[] s) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(s[0]));
    MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
    while (reader.ready()) {
      String[] fields = reader.readLine().split("\t");
      ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
      System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);      
    }
  }

  public MetaDataToTldLinks() {
    this.parser = new JsonParser();
  }

  public ParseResult outboundLinks(String jsonMetaData) {
    JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();

    if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
      return NO_LINKS;

    JsonElement content = metaData.get("content");
    if (content == null)
      return NO_LINKS;

    JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
    if (links == null)
      return NO_LINKS;

    Set<String> outboundLinks = new HashSet<String>();
    int numNull = 0;
    for (JsonElement linke : links) {
      JsonObject link = linke.getAsJsonObject();
      if ("a".equals(link.get("type").getAsString())) { // anchor        
        String tld = tldOf(link.get("href").getAsString());
        if (tld == null)
          ++numNull;
        else
          outboundLinks.add(tld);
      }
    }
    return new ParseResult(outboundLinks, numNull);

  }

  public static String tldOf(String url) {
    try {
      String tld = new URI(url).getHost();
      if (tld==null)
          return null;
      if (tld.startsWith("www."))
        tld = tld.substring(4);
      tld = tld.trim();
      return tld.length()==0 ? null : tld;
    }
    catch (URISyntaxException e) {
      return null;
    }
  }

  public static class ParseResult {
    public final Set<String> links;
    public final int numNull;
    public ParseResult(Set<String> links, int numNull) {
      this.links = links;
      this.numNull = numNull;
    }
  }

答案 1 :(得分:1)

这个snippet怎么样?:

if (json.isJsonArray()) {
  JsonArray array = json.getAsJsonArray();
  List<Object> out = Lists.newArrayListWithCapacity(array.size());
  for (JsonElement item : array) {
    out.add(toRawTypes(item));
   }
}