首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当对象名为整数时,Java GSON反序列化JSON

当对象名为整数时,Java GSON反序列化JSON
EN

Stack Overflow用户
提问于 2018-10-04 01:39:54
回答 4查看 280关注 0票数 1

首先,我大体上知道如何反序列化JSON对象。我遇到的具体问题是,我有一个Json对象,其中包含名为"1", "2", "3"等的数组,但在Java语言中,我不能声明变量ArrayList<AnotherObject> 1;。有没有比手动替换数字更好的方法?

Json (大大减少):

代码语言:javascript
复制
{
    "object": {
        "1": [{...}],
        "2": [{...}],
        "3": [{...}],
        "4": [{...}],
        "5": [{...}],
        "6": [{...}],
        "7": [{...}]
    }
}

提前感谢

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-10-04 04:27:43

下面是使用GSON反序列化JSON的方法:

代码语言:javascript
复制
public static void main(String[] args) {
    final String json = "{\n" +
        "    \"object\": {\n" +
        "        \"1\": [{ \"id\" : 111 }],\n" +
        "        \"2\": [{ \"id\" : 222 }],\n" +
        "        \"3\": [{ \"id\" : 333 }]\n" +
        "    }\n" +
        "}\n";
    final Gson gson = new GsonBuilder()
        .create();
    final ObjectWrapper value = gson.fromJson(json, ObjectWrapper.class);

    System.out.println(value.object);
    System.out.println(value.object.keySet());
    System.out.println(value.object.get(1));
}

// This is top-most object we want to deserialize from JSON
static class ObjectWrapper {
    // Didn't bother about proper naming while it is better to give a meaningful name here
    private Map<Integer, List<Element>> object;
}

static class Element {
    // Added this attribute to demonstrate that objects within array are properly read
    private int id;
    @Override
    public String toString() {
        return "{id=" + id + "}";
    }
}
票数 1
EN

Stack Overflow用户

发布于 2018-10-04 01:42:37

这些数字看起来很像数组的索引。如果是这样的话,你可以把它们全部删除,然后把整个对象变成一个数组。所以你会得到一个数组的数组。

票数 0
EN

Stack Overflow用户

发布于 2018-10-04 02:52:32

我现在使用以下解决方法:

代码语言:javascript
复制
json.replace("\"1\"","\"one\"")
    .replace("\"2\"","\"two\"")
    .replace("\"3\"","\"three\"")
    .replace("\"4\"","\"four\"")
    .replace("\"5\"","\"five\"")
    .replace("\"6\"","\"six\"")
    .replace("\"7\"","\"seven\"");

编辑:这个解决方案确实有效,但它相当丑陋。@yegodm的解决方案效果要好得多!谢谢你这么做!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52632785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档