2

我不知道如何使用 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>

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

4

2 回答 2

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/

于 2011-03-11T10:35:41.970 回答
0

这里有几个问题:

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

数组可能应该是这样的:

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

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

您示例中数组的问题在于它不是同质的......它有一个数字和两个字符串。通常,应避免在数组/集合中混合此类类型。但是,您可以将array对象的类型声明为List<String>... 您只会得到String数字的形式。

于 2010-10-17T01:58:50.813 回答