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

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

问题描述

我有一个这样的 JSON 文件:

<预><代码>[{"number": "3","title": "hello_world",}, {2号","title": "hello_world",}]

在文件具有根元素之前,我会使用:

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

code 但我不知道如何编写 Wrapper 类,因为根元素是一个数组.

我试过使用:

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

与:

公共类包装器{字符串编号;字符串标题;}

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

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

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

但我更想知道如何使用这两种方法(如果可能).

解决方案

问题是由放置在数组中的 JSON 对象(在您的情况下each)末尾的逗号引起的:

<代码>{数字": "...","title": ".." ,//<- 看到那个逗号了吗?}

如果您删除它们,您的数据将变成

<预><代码>[{"number": "3","title": "hello_world"}, {2号","title": "hello_world"}]

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

应该可以正常工作.

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.fromJson(JSONSTRING, Wrapper.class);

code but I can't think how to code the Wrapper class as the root element is an array.

I have tried using:

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

with:

public class Wrapper{

    String number;
    String title;

}

But haven't had any luck. How else can I read this using this method?

P.S I have got this to work using:

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

But I would prefer to know how to do it (if possible) with both methods.

解决方案

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
    "number": "...",
    "title": ".." ,  //<- see that comma?
}

If you remove them your data will become

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

and

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

should work fine.

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

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