[英]Parsing JSON array with a sub-array with GSON?
假設我有一個JSON字符串,如:
{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"200"}, ...
我的訪問者:
import com.google.gson.annotations.SerializedName;
public class accessorClass {
@SerializedName("title")
private String title;
@SerializedName("url")
private String url;
@SerializedName("image")
private String image;
// how do I place the sub-arrays for the image here?
...
public final String get_title() {
return this.title;
}
public final String get_url() {
return this.url;
}
public final String get_image() {
return this.image;
}
...
}
我的主要人物:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jstring).getAsJsonArray();
ArrayList<accessorClass > aens = new ArrayList<accessorClass >();
for(JsonElement obj : Jarray )
{
accessorClass ens = gson.fromJson( obj , accessorClass .class);
aens.add(ens);
}
您認為在這里獲取圖像的子陣列的最佳方法是什么?
僅供參考,如果你的JSON是一個數組: {"results:":[{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}
然后你需要一個包裝類:
class WebServiceResult {
public List<AccessorClass> results;
}
如果你的JSON沒有像那樣格式化,那么你創建的For循環就會這樣做(如果你的JSON形成的話,如果不是有點笨重的話會更好)。
創建一個Image類
class ImageClass {
private String url;
private int width;
private int height;
// Getters and setters
}
然后更改您的AccessorClass
@SerializedName("image")
private ImageClass image;
// Getter and setter
然后GSON傳入String
Gson gson = new Gson();
AccessorClass object = gson.fromJson(result, AccessorClass.class);
任務完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.