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

标签 java json gson

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

Json(大大减少):

{
    "object": {
        "1": [{...}],
        "2": [{...}],
        "3": [{...}],
        "4": [{...}],
        "5": [{...}],
        "6": [{...}],
        "7": [{...}]
    }
}

提前致谢

最佳答案

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

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 + "}";
    }
}

关于当对象名称为整数时,Java GSON 反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52632785/

相关文章:

java - 制定在某一天开始的 Activity

java - 切入点表达式内有多个执行语句,但只有一个正在运行

asp.net - Javascript JSON.stringify 对象包含数组序列化问题

java - 使用 GSON 解析 JSON 文件

java - 将A系统作为Tomcat服务器

json - 使用 Rails 3 应用程序的 ios json 身份验证

json - 导出 JSON 数据并加载到关系数据库中

android - 如何在改造中处理动态 JSON?

java - 使用 GSON JsonReader 处理巨大字段的最佳方式

java - Spring Data JPA 与 H2 数据库 : Connect two Entities in different Projects