猿问

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

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


Json(大大减少):


{

    "object": {

        "1": [{...}],

        "2": [{...}],

        "3": [{...}],

        "4": [{...}],

        "5": [{...}],

        "6": [{...}],

        "7": [{...}]

    }

}

提前致谢


青春有我
浏览 157回答 3
3回答

白板的微信

这是您可以GSON用来反序列化 JSON 的方法:public static void main(String[] args) {&nbsp; &nbsp; final String json = "{\n" +&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; \"object\": {\n" +&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; \"1\": [{ \"id\" : 111 }],\n" +&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; \"2\": [{ \"id\" : 222 }],\n" +&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; \"3\": [{ \"id\" : 333 }]\n" +&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; }\n" +&nbsp; &nbsp; &nbsp; &nbsp; "}\n";&nbsp; &nbsp; final Gson gson = new GsonBuilder()&nbsp; &nbsp; &nbsp; &nbsp; .create();&nbsp; &nbsp; final ObjectWrapper value = gson.fromJson(json, ObjectWrapper.class);&nbsp; &nbsp; System.out.println(value.object);&nbsp; &nbsp; System.out.println(value.object.keySet());&nbsp; &nbsp; System.out.println(value.object.get(1));}// This is top-most object we want to deserialize from JSONstatic class ObjectWrapper {&nbsp; &nbsp; // Didn't bother about proper naming while it is better to give a meaningful name here&nbsp; &nbsp; private Map<Integer, List<Element>> object;}static class Element {&nbsp; &nbsp; // Added this attribute to demonstrate that objects within array are properly read&nbsp; &nbsp; private int id;&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "{id=" + id + "}";&nbsp; &nbsp; }}

慕无忌1623718

我现在使用以下解决方法:json.replace("\"1\"","\"one\"")    .replace("\"2\"","\"two\"")    .replace("\"3\"","\"three\"")    .replace("\"4\"","\"four\"")    .replace("\"5\"","\"five\"")    .replace("\"6\"","\"six\"")    .replace("\"7\"","\"seven\"");

湖上湖

这些数字看起来很像数组的索引。如果是这样,您可以删除所有这些对象并使整个对象成为一个数组。所以你会得到一个数组数组。
随时随地看视频慕课网APP

相关分类

Java
我要回答