首页 > 解决方案 > 如何在没有密钥的情况下在android中解析JSONArray

问题描述

我有这样的服务器响应:

[
  "test1",
  [
    "test2",
    "test3",
    "test4"
  ]
]

我尝试解析对 JSONObject 的响应,但是当记录jsonObject.toString()时,它没有显示任何内容。所以我只是用 JSONArray 解析响应并想在 RecyclerView 中显示:

JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
     DataModel dataModel = new DataModel();
     dataModel.setId(i);
     dataModel.setWord(jsonArray[i]);
     temp.add(dataModel);
}

但我在jsonArray[i]上有错误。我可以从一开始,这样做:

JSONArray jsonArray = new JSONArray(response);
response = jsonArray.toString().replaceAll(" []" ", "");
String[] words = response.split(",");

并通过 for 循环,将数据添加到 RecyclerView。但是,如果响应中的单词包含{"},则以这种方式将其删除。如何削减这个 json?

标签: androidjson

解决方案


虽然 JSON 是有效的,但它的结构很奇怪。我不确定您是否可以将此 JSON 放入一致的数据模型中。

看起来第一个元素是 aString而第二个元素是另一个列表。因此,您可以执行以下操作。

List<String> allElements = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
    try {
        // Try to parse it to an array
        JSONArray elementArr = new JSONArray(jsonArray[i]);
        for (int j = 0; j < elementArr.length(); j++) {
            // I hope the nested JSON array is not messed up!! 
            allElements.add(elementArr[j]);
        }

    } catch (Exception e) {
        // The element is not an array, hence add it to the list directly
        allElements.add(jsonArray[i]);
    }
}

最后,allElements应该有你想要的所有字符串。


推荐阅读