我有这样一个JSON文件:

[
    {
        "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.

我试过使用:

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

使用:

public class Wrapper{

    String number;
    String title;

}

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

附注:我使用以下命令使此功能正常工作:

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?
}

如果你删除它们,你的数据将变得

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

and

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

should work fine.

Json相关问答推荐

仅在通过Jolt输入时才级联Json的值

PowerShell脚本-替换json数组(转义$var将被视为不带双引号的文本)

服务器不返回JSON

如何在Vega中使标记的符号在鼠标指针悬停时可点击

在AWS步骤函数中将字符串解析为JSON&S映射状态

在Ansible中从json中提取特定数据

将PNG图像保存为Python中的JSON文件

Android 如何判断小时时间是否在两个时间之间?

如何将具有相同 struct 的多个JSON文件中的对象数组合并成一个数组?

使用 jq 工具将文本从 txt 文件转换为 json

将 json 文件转换为 json 对象会打乱对象的顺序

使用 JQ 从文件中删除重复的 JSON 块

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

Google GCM 服务器返回未经授权的错误 401

如何使用 gson 将数据保存在 json 文件中?

解析包含换行符的 JSON

使用 simplejson 序列化简单类对象的最简单方法?

在 Jersey 服务中使用 JSON 对象

js 中奇怪的 JSON 解析行为,Unexpected token :

将多个值存储在json中的单个键中