繁体   English   中英

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

[英]How can I deserialize an array inside a JSON object?

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

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

您的“数组”是一个数组。 所以在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/

这里有两个问题:

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

该数组应该类似于:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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