【问题标题】:Java with GSON - deserialize only the values into an ArrayList of a JSON string带有 GSON 的 Java - 仅将值反序列化为 JSON 字符串的 ArrayList
【发布时间】:2013-03-06 19:49:58
【问题描述】:

我的 JSON 响应字符串的结构如下:

{
    "1":{
        "data1":"1","data2":"test1", ...
    },
    "2":{
        "data1":"6","data2":"test2", ...
    },
    ...
}

我想让 放入 ArrayList<MyItem>。我使用 GSON,通常我可以这样做:

ArrayList<MyItem> items = 
    gson.fromJson(jsonString, new TypeToken<ArrayList<MyItem>>() {}.getType());

问题是,它不起作用,因为我的 JSON 字符串有数字作为键,但我只想获取要放入 ArrayList 的值(不幸的是,我无法更改 JSON 字符串) .我怎样才能有效地做到这一点?

【问题讨论】:

  • 为什么不尝试将 json 放入 Map&lt;Integer, ArrayList&lt;MyItem&gt;&gt; map 然后 List&lt;MyItems&gt; map = foreach(..)

标签: java json arraylist deserialization gson


【解决方案1】:

我可能会将 JSON 反序列化为 java.util.Map,使用 the Map.values() methodMap 获取值作为 Collection,然后使用 the constructor that takes a Collection 创建新的 ArrayList

【讨论】:

  • 我是这样做的。我想,有更好的解决方案,但我也没有找到。
【解决方案2】:

编写自定义反序列化器。

class MyItem 
{
    String data1;
    String data2;
    // ...
}

class MyJSONList extends ArrayList<MyItem> {}

class MyDeserializer implements JsonDeserializer<MyJSONList> 
{
    public MyJSONList deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) 
        throws JsonParseException
    {
        MyJSONList list = new MyJSONList();
        for (Entry<String, JsonElement> e : je.getAsJsonObject().entrySet())
        {
            list.add((MyItem)jdc.deserialize(e.getValue(), MyItem.class));
        }

        return list;
    }

}

例子:

String json = "{\"1\":{\"data1\":\"1\",\"data2\":\"test1\"},\"2\":{\"data1\":\"6\",\"data2\":\"test2\"}}";
Gson g = new GsonBuilder()
            .registerTypeAdapter(MyJSONList.class, new MyDeserializer())
            .create();
MyJSONList l = g.fromJson(json, MyJSONList.class);


for (MyItem i : l)
{
    System.out.println(i.data2);
}

输出:

测试1
测试2

【讨论】:

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