[英]Count number of Strings and JSONObjects in JSONArray
我正在嘗試解析JSON模式,我需要從JSONArray獲取所有圖像鏈接並將其存儲在Java數組中。 JSONArray看起來像這樣:
我怎樣才能獲得圖像數組中的字符串數量,例如,在這種情況下它應該是4? 我知道如何獲得數組的全長,但我怎么才能得到字符串的數量?
更新:
我只是使用標准的JSON解析器為android解析它。 JSONArray的長度可以使用以下公式計算:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
在這種情況下, len
將等於9。
我不確定是否有更好的方法(可能有),但這里有一個選擇:
根據Android文檔 ,如果指定索引處的元素不是JSON對象,則getJSONObject
將拋出JSONException
。 因此,您可以嘗試使用getJSONObject
獲取每個索引處的元素。 如果它拋出JSONException
,那么您知道它不是JSON對象。 然后,您可以嘗試使用getString
獲取元素。 這是一個粗略的例子:
JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();
ArrayList<String> imageLinks = new ArrayList<String>();
for (int i = 0; i < len; i++) {
boolean isObject = false;
try {
JSONArray obj = imageArray.getJSONObject(i);
// obj is a JSON object
isObject = true;
} catch (JSONException ex) {
// ignore
}
if (!isObject ) {
// Element at index i was not a JSON object, might be a String
try {
String strVal = imageArray.getString(i);
imageLinks.add(strVal);
} catch (JSONException ex) {
// ignore
}
}
}
int numImageLinks = imageLinks.size();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.