如何通过gson解析具有多个对象的json数组?
如何使用gson解析json?我有一个具有多种对象类型的json数组,但我不知道我需要创建哪种对象来保存此结构。我无法更改json数据格式(我不控制服务器)。我可以使用gson或其他库解析此json数组,怎么办?
这是json代码块:
[  {
    "type": 1,
    "object": {
      "title1": "title1",
      "title2": "title2"
    }
  },
  {
    "type": 2,
    "object": [
      "string",
      "string",
      "string"
    ]
  },
  {
    "type": 3,
    "object": [
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      },
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      }
    ]
  },
  {
    "type": 4,
    "object": {
      "id": 337203,
      "type": 1,
      "city": "1"
    }
  }
]
回答:
这个json结构本质上是gson不友好的。即您不能在Java中对此进行清晰建模,因为“对象”键引用了动态类型。您可以使用此结构做的最好的事情就是像这样建模:
    public class Models extends ArrayList<Models.Container> {    public class Container {
        public int type;
        public Object object;
    }
    public class Type1Object {
        public String title1;
        public String title2;
    }
    public class Type3Object {
        public String url;
        public String text;
        public int width;
        public int height;
    }
    public class Type4Object {
        public int id;
        public int type;
        public int city;
    }
}
然后在type和object字段上进行一些尴尬的切换:
String json = "{ ... json string ... }";Gson gson = new Gson();
Models model = gson.fromJson(json, Models.class);
for (Models.Container container : model) {
    String innerJson = gson.toJson(container.object);
    switch(container.type){
        case 1:
            Models.Type1Object type1Object = gson.fromJson(innerJson, Models.Type1Object.class);
            // do something with type 1 object...                                
            break;
        case 2:
            String[] type2Object = gson.fromJson(innerJson, String[].class);
            // do something with type 2 object...
            break;
        case 3:
            Models.Type3Object[] type3Object = gson.fromJson(innerJson, Models.Type3Object[].class);
            // do something with type 3 object...
            break;
        case 4:
            Models.Type4Object type4Object = gson.fromJson(innerJson, Models.Type4Object.class);
            // do something with type 4 object...
            break;
    }
}
最终,最好的解决方案是将json结构更改为与Java更兼容的东西。
例如:
[  {
    "type": 1,
    "type1Object": {
      "title1": "title1",
      "title2": "title2"
    }
  },
  {
    "type": 2,
    "type2Object": [
      "string",
      "string",
      "string"
    ]
  },
  {
    "type": 3,
    "type3Object": [
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      },
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      }
    ]
  },
  {
    "type": 4,
    "type4Object": {
      "id": 337203,
      "type": 1,
      "city": "1"
    }
  }
]
以上是 如何通过gson解析具有多个对象的json数组? 的全部内容, 来源链接: utcz.com/qa/402886.html

