簡體   English   中英

在Android上使用GSON解析JSON嵌套數組

[英]Parsing JSON nested array with GSON on Android

我瀏覽了該論壇,並遇到了一些類似的問題,但是沒有一個有幫助。

所以我要從其他人離開的地方開始工作,這就是問題所在。 我正在處理的代碼使用gson解析json流,這很清楚,然后將相關數據添加到一個包裹中。 像下面

public class JsonAssets{

    String Address;
    String Title;
    String File;
    Category [] Categories;

public void writeToParcel(Parcel paramParcel, int paramInt) {

    paramParcel.writeString(Address);
    paramParcel.writeString(Title);
    paramParcel.writeString(AudioFile);
}


private JsonAsset(Parcel in) {

    Address = in.readString();
    Title = in.readString();
    AudioFile = in.readString();
}

public ContentValues getContentValues(){

    ContentValues contentValue = new ContentValues();
    contentValue.put("ID", this.Id);
    contentValue.put("Title", this.Title);
    contentValue.put("address", this.Address);
}

編輯

private class Category{

   String CategoryName;
   String Description;
   String ExternalLink;
   String File;
   String FileName;
   int    CategoryID;
   int    ParentCategoryID;
   int    Id;
   int    Image;

public int getCategoryID(){

return this.Id;

}

}

然后,使用這些contentValues更新數據庫。

JSON看起來像這樣:

"assets":[
      {
         "Address":"Crator1, The Moon",
         "Title":"The Moon",
         "AudioFile":null,
         "Categories":[
            {
               "CategoryName":"Restaurants",
               "Description":"blah blah",
               "ExternalLink":"",
               "File":"",
               "FileName":"0",
               "CategoryID":0,
               "ParentCategoryID":786,
               "Id":334,
               "Image":"",
            },

我知道JSON無效,我只是對其進行了編輯。 問題是我有類別,一個嵌套的數組,我不知道如何處理該數組。 我想要獲取的只是Categories數組中的“ Id”。

由於類的傳遞方式,我無法為其創建單獨的對象:

JsonReader reader =新的JsonReader(new InputStreamReader(is,“ UTF-8”));

    reader.beginObject();
    reader.nextName();
    reader.beginArray();
    JsonObject obj = null;


    while (reader.hasNext()) {
        try{
            switch(type){
            case ASSET_UPDATE:
                obj = gson.fromJson(reader, JsonAsset.class);

                break;
            }

因此,如果有人可以告訴我如何處理此問題,我將不勝感激。 如果我在道歉問題上不太清楚,請問一下,我會先澄清一下...謝謝

1)將obj聲明為您真正擁有的類(JsonAsset)

JsonAsset obj = gson.fromJson(reader, JsonAsset.class);

2)修改類以匹配Json字符串

public class JsonAssets{

String Address;
String Title;
String AudioFile;
Category[] Categories;
}

private class Category{

String CategoryName;
...
}

fromJson將返回帶有嵌套數組的完整初始化對象

因此,經過數小時令人心碎的研究,我設法正確回答了自己的問題。

如果有人遇到相同的問題,請點擊此鏈接:
http://www.javacreed.com/gson-deserialiser-example/

它照顧了1:正確解析嵌套數組,並且還為我反序列化了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM