有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java统计JSONArray中字符串和JSONObject的数量

我试图解析JSON模式,需要从JSONArray获取所有图像链接,并将其存储在java数组中。JSONArray如下所示:

enter image description here

如何仅获取图像数组中的字符串数,例如,在本例中,字符串数应为4?我知道如何获取数组的完整长度,但如何仅获取字符串数

更新:

我只是使用安卓的标准JSON解析器对其进行解析。JSONArray的长度可以使用以下公式计算:

JSONArray imageArray = hist.getJSONArray("image");
int len = imageArray.length();

在这种情况下len将等于9


共 (1) 个答案

  1. # 1 楼答案

    我不确定是否有更好的方法(可能有),但这里有一个选择:

    根据the Android docsgetJSONObject将在指定索引处的元素不是JSON对象时抛出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();