[英]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.