[英]Parsing JSON array with a sub-array with GSON?
Say I have a JSON string like: 假设我有一个JSON字符串,如:
{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"200"}, ...
My accessor: 我的访问者:
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;
}
...
}
And my main: 我的主要人物:
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);
}
What do you think would be the best way to get those sub-arrays for the image here? 您认为在这里获取图像的子阵列的最佳方法是什么?
FYI if your JSON is an array: {"results:":[{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}
仅供参考,如果你的JSON是一个数组:
{"results:":[{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}
Then you need a wrapper class: 然后你需要一个包装类:
class WebServiceResult {
public List<AccessorClass> results;
}
If your JSON isn't formatted like that, then your For loop you created will do it, (if not a little clunky, would be better if your JSON is formed like above). 如果你的JSON没有像那样格式化,那么你创建的For循环就会这样做(如果你的JSON形成的话,如果不是有点笨重的话会更好)。
Create an Image class 创建一个Image类
class ImageClass {
private String url;
private int width;
private int height;
// Getters and setters
}
Then change your AccessorClass
然后更改您的
AccessorClass
@SerializedName("image")
private ImageClass image;
// Getter and setter
Then GSON the incoming String 然后GSON传入String
Gson gson = new Gson();
AccessorClass object = gson.fromJson(result, AccessorClass.class);
Job done. 任务完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.