在Android上使用GSON解析JSON嵌套数组

时间:2013-12-04 15:30:58

标签: android json gson

我已经浏览了论坛,并且遇到了一些类似的问题但没有任何帮助。

所以我从其他人离开的地方开始,这就是问题所在。我正在处理的代码使用gson来解析json流,这很好而且很清晰,然后将相关数据添加到一个parcel中。如下所示

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无效,我刚编辑以适应。问题是我有类别,嵌套数组,我不知道如何处理该数组。我想要得到的是类别数组中的'Id'。

由于传递类的方式,我无法为它创建一个单独的对象:

JsonReader reader = new 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;
            }

所以如果有人能告诉我如何处理这个问题,我会非常感激。如果我在我的问题上不太清楚道歉,那就问一下,我会澄清......提前谢谢

2 个答案:

答案 0 :(得分:4)

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将返回一个带有嵌套数组的完整初始化对象

答案 1 :(得分:1)

因此,经过几个小时的令人心碎的研究,我设法正确地回答了我自己的问题。

如果有人遇到同样的问题,请点击此链接:
http://www.javacreed.com/gson-deserialiser-example/

它负责1:正确解析嵌套数组,并且它也为我反序列化了。