簡體   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