我得到了不同结构的JSON。一个是画廊,但其他没有。
第一个JSON :(没有图库)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
第二个JSON(带图库)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"gallery": [
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.pngg",
"www.example.com/img1.png"
],
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
我把这个JSON放到这样的数组中:
data = whole JSON file, which I get from web service
JSONObject jRealObject = new JSONObject(data);
title = jRealObject.getString("title").toString();
text = jRealObject.getString("fulltext").toString();
JSONArray jArray = jRealObject.getJSONArray("gallery");
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}
JSONArray jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
relatedId[i] = jRealObject.getString("id").toString();
relatedTitle[i] = jRealObject.getString("title").toString();
relatedImage[i] = jRealObject.getString("image_name").toString();
}
因此,当我通过画廊获得JSON时,它的工作非常完美,但是当文章没有画廊时,我会例外:
W/System.err(30635): org.json.JSONException: No value for gallery
如果有&#34;画廊&#34>我如何检查?在JSON ??
答案 0 :(得分:1)
你可以使用GSON库,这个库是对象的json解析,非常强 。
这里有一个示例,您可以使用json响应实现此库。
答案 1 :(得分:0)
JSONArray jArray = jRealObject.optJSONArray("gallery",null);
if(jArray != null)
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}