【问题标题】:Using GSON to parse a JSON array使用 GSON 解析 JSON 数组
【发布时间】:2013-08-27 14:49:05
【问题描述】:

我有一个这样的 JSON 文件:

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

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

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

代码,但我想不出如何将Wrapper 类编码为根元素是一个数组。

我尝试过使用:

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

与:

public class Wrapper{

    String number;
    String title;

}

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

P.S 我可以使用:

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

但我更愿意知道如何使用这两种方法(如果可能的话)。

【问题讨论】:

  • 你确定标题元素后面有逗号吗?如果你删除它们 Wrapper[] data = gson.fromJson(jElement, Wrapper[].class); 对我来说很好。
  • 这就是问题所在.. 这么简单的错误!

标签: java arrays json gson


【解决方案1】:

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

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

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

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

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

应该可以正常工作。

【讨论】:

【解决方案2】:
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

似乎工作正常。但是你的字符串中有一个额外的, 逗号。

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

【讨论】:

    【解决方案3】:
    public static <T> List<T> toList(String json, Class<T> clazz) {
        if (null == json) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<T>(){}.getType());
    }
    

    示例调用:

    List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
    

    【讨论】:

    • 对我来说,这是将我的对象变成 LinkedTreeMap 列表而不是规范对象列表(例如)。
    • 你从哪里得到 GsonUtils 类的?
    • GsonUtils 是他放置自己的toList() 方法的类。
    • 这不起作用:TypeToken 必须创建一个错误的值,因为 T 在编译时是未知的。这可能会为 List 创建类型标记。创建类型时必须使用实际的类。
    【解决方案4】:
    Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多