android - 如何在没有密钥的情况下在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?
解决方案
虽然 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
应该有你想要的所有字符串。
推荐阅读
- c# - Avalondock - 某些面板的延迟布局恢复
- bootstrap-4 - Bootstrap Algn 元素水平问题
- kubernetes - Kubernetes 中用户或角色的命名空间
- php - 如何从 PHP 中的数组中获取前 3 个位置(值),包括重复
- c# - 如何在join中调用另一个函数
- python - How can I replace the first occurrence of a character in every word?
- powershell - Outputting Disk Usage in Powershell
- python - sort list of integers that are value to a key in dictionary python
- javascript - 试图加载一些数据
- python - 如何使用 python 从命令行读取 excel 文件?