How can I deserialize an array inside a JSON object?

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

I can't work out how to deserialize an array inside a JSON object using Gson. The json object that i'm trying to deserialize looks like this:

{"item0":3,  "item1":1,  "item2":3,  "array":[     {"arrayItem1":321779321,      "arrayItem2":"asdfafd",      "arrayItem3":"asasdfadf"}]} 

I manage to build a class that looks like this:

public class Watchlist {  private int itemn0;  private int itemn1;  private int itemn2;  private Object array;  } 

But when gson tries to deserialize the array it throws an exception:

com.google.gson.JsonParseException: Type information is unavailable, and the target object is not a primitive: 

Can someone please tell me how to deserialize this?

回答1:

your "array" is an Array. so in watchList class

    public class Watchlist {     private int itemn0;     private int itemn1;     private int itemn2;     private List array;   //constructor   //getter & setter of all  }  now watchListarray class  public class watchListarray{   String arrayItem1="";   String arrayItem2="";   String arrayItem3=""; //constructor   //getter & setters of all } 

Now use download Gson refer: http://primalpop.wordpress.com/2010/06/05/parsing-json-using-gson-in-android/



回答2:

There's a couple of problems here:

One, I don't think you're using the array like you think you are. You have "arrayItem1" through 3, but they are contained in a single JSON object within the array... so the array actually only has one item.

The array should probably be something like:

"array": [   321779321,   "asdfafd",   "asasdfadf" ] 

The second is that the type of array in your Java class is Object... that doesn't give Gson any type information to use for translating the object. Normally, you'd want to declare the type of the object the array maps to as List or List or some such. This gives it the necessary type information... a JSON array can map to a List, and the String type parameter tells it what type to translate the array's contents to.

The problem with the array in your example is that it isn't homogenous... it has a number and two strings in it. Generally, mixing types like this in an array/collection should be avoided. You can, however, declare the type of your array object as List... you'll just get the String form of the number.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!