java - org.json.JSONObject 不能转换为 java.util.Map
问题描述
将 Map 转换为 Android 应用程序的 JSONObject。构建但在运行时崩溃。查看Logcat并得到错误:
org.json.JSONObject 不能转换为 java.util.Map
这是相关的部分:
JSONObject item = new JSONObject(data);
Map product = ((Map)item.get("product"));
正是第二行导致它崩溃。我注释掉了代码,直到取消注释该行导致崩溃。
它链接到的 JSON 在这里。
取消映射 JSONObject 会出现此错误:
不兼容的类型。
必需:java.util.Map<,>
找到:java.lang.Object
更广泛的代码视图:
TextView parsed = findViewById(R.id.jsonParse);
String barcodeNum = result.getText();
String productName = "";
try {
URL url = new URL("https://world.openfoodfacts.org/api/v0/product/" + barcodeNum + ".json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String data = "";
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONObject item = new JSONObject(data);
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> map =
product.keySet()
.stream()
.collect(Collectors.toMap(
Function.identity(),
product::get
));
解决方案
JSONObject#get
不会返回 a Map
。相反,它将返回另一个JSONObject
描述嵌套product
属性的 。
你会看到,确实,它可以被投射到它上面
final JSONObject product = (JSONObject) item.get("product");
你能做的是
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> objectMap = product.toMap();
在不提供该toMap
方法的旧版本 JSON-Java 上,您可以做的是
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> map =
product.keySet()
.stream()
.collect(Collectors.toMap(
Function.identity(),
product::get
));
推荐阅读
- c# - 如何在 C# TableAdapter 向导中使用子查询计算匹配记录
- javascript - 在 JavaScript 中阻止每 X 秒调用一次函数的最简单方法是什么?
- python - 如何修复“GurobiError Q 矩阵不是半正定 (PSD)”
- java - 返回导致 NullPointerException 的 ArrayList 的方法
- bash - BASH - 在 for 循环问题中查找文件
- c# - C# 中是否存在表示从字符串转换时出错的浮点数?
- django - Django Permission denied: '/media/images' 上传图片
- reactjs - 如何减少按钮的数量?
- android - 如何开始为 Google Glass 开发应用程序?
- assembly - 如何将数字类型位置设置为 x,y 类型位置?