如何使用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; }}
然后在类型和对象字段上做一些尴尬的开关:
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" } }]
总结 以上是内存溢出为你收集整理的java – 如何用gson解析带有多个对象的json数组?全部内容,希望文章能够帮你解决java – 如何用gson解析带有多个对象的json数组?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)