如何反序列化JSON对象中的数组?

时间:2010-10-17 00:50:14

标签: java json gson

我无法弄清楚如何使用Gson反序列化JSON对象中的数组。我正在尝试反序列化的json对象看起来像这样:

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

我设法建立一个如下所示的类:

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

}

但是当gson尝试反序列化数组时会引发异常:

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

有人可以告诉我如何反序列化吗?

2 个答案:

答案 0 :(得分:1)

你的“数组”是一个数组。 所以在watchList类

    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
}

现在使用下载Gson 参考:http://primalpop.wordpress.com/2010/06/05/parsing-json-using-gson-in-android/

答案 1 :(得分:0)

这里有几个问题:

一,我不认为你像你认为的那样使用阵列。你有“arrayItem1”到3,但是它们包含在数组中的一个JSON对象中......所以数组实际上只有一个项目。

数组可能应该是这样的:

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

第二个是Java类中array的类型是Object ...它不会为Gson提供任何用于翻译对象的类型信息。通常,您需要声明数组映射到的对象的类型为List<String>List<Integer>或其他类型。这为它提供了必要的类型信息...... JSON数组可以映射到ListString类型参数告诉它将数组内容转换为什么类型。

你的例子中数组的问题是它不是同质的......它有一个数字和两个字符串。通常,应避免在阵列/集合中使用这样的混合类型。但是,您可以将array对象的类型声明为List<String> ...您只需获取该号码的String形式。