Gson Parse Json with array with different object types

后端 未结 5 1357
梦毁少年i
梦毁少年i 2020-12-09 10:16

How can I parse this JSON using Gson? I have an array with multiple object types and I don\'t know what kind of object I need to create to save this structure. I cannot cha

5条回答
  •  既然无缘
    2020-12-09 10:25

    Try this code here:

    public class Address {
        public String userId;
        public String address;
        // ...
    }
    
    public class Response {
        private HashMap tr;
        private int results;
        // ...
    }
    

    Usage:

    String json = "{\n  \"tr\":\n  {\n    \"a\": {\n       \"userId\": \"112\"\n    },\n    \"b\": {\n       \"userId\": \"123\",\n       \"address\":\"street dummy\"\n    },\n    \"c\": {\n       \"userId\": \"154\"\n    }\n  },\n  \"results\":3\n}";
    
    Response users = new Gson().fromJson(json, Response.class);
    

    As you may see I needed to modify the structure:

    {
      "tr":
      {
        "a": {
           "userId": "112"
        },
        "b": {
           "userId": "123",
           "address":"street dummy"
        },
        "c": {
           "userId": "154"
        }
      },
      "results":3
    }
    

    But unfortunately I don't get it managed to allow multiple keys. Right now I have no idea how to fix this.

提交回复
热议问题