简体   繁体   中英

How can I deserialize an array inside a JSON object?

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: <my gson array>

Can someone please tell me how to deserialize this?

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

    public class Watchlist {
    private int itemn0;
    private int itemn1;
    private int itemn2;
    private List<watchListarray> 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/

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<String> or List<Integer> 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<String> ... you'll just get the String form of the number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM