使用GSON解析JSON数组 [英] Using GSON to parse a JSON array

查看:161
本文介绍了使用GSON解析JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个JSON文件:

I have a JSON file like this:

[{ "number" : "3",
    "title" : "hello_world",

  },
  { "number" : "2",
    "title" : "hello_world",

  }]

在文件时有一个根元素,我会用:

Before when files had a root element i would use:

Wrapper w = gson.ftomJson(JSONSTRING, Wrapper.class);

code,但我不能想怎么code中的包装类作为根元素是一个数组

code but i cant think how to code the Wrapper class as the root element is an array

我已经尝试使用:

Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);

public class Wrapper{

    String number;
    String title;

}

但还没有任何运气。我还能如何阅读本使用这种方法?

But havent had any luck. How else can i read this using this method?

P.S我有这个使用的工作:

P.S i have got this to work using:

JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");

但我会preFER知道如何使用这两种方法做到这一点(如果可能)

but i would prefer to know how to do it (if possible) with both methods

推荐答案

问题是用逗号阵列的最后一个元素之后造成的(后每个标题)。如果你删除它,你的数据更改为

Problem is caused by comma after last element of your array (after each title). If you remove it and change your data to

[{ "number" : "3",
  "title" : "hello_world"  
},
{ "number" : "2",
  "title" : "hello_world"  
}]

包装[]数据= gson.fromJson(jElement,包装[]类);
将正常工作。

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class); will work fine.

这篇关于使用GSON解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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