将 map 转换为 Android 应用程序的 JSONObject。构建但在运行时崩溃。查看Logcat并得到错误:
org.json.JSONObject cannot be cast to java.util.Map
这是相关部分:
JSONObject item = new JSONObject(data);
Map product = ((Map)item.get("product"));
特别是第二行导致它崩溃。我注释掉了代码,直到取消注释该行导致崩溃。
它链接到的 JSON 是 here .
取消映射 JSONObject 会出现此错误:
Incompatible types.
Required: java.util.Map<, >
Found: java.lang.Object
更广泛的代码 View :
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
不会返回 map
。相反,它将返回另一个 JSONObject
,它描述了嵌套的 product
属性。
你会看到,确实,它可以被转换到它
final JSONObject product = (JSONObject) item.get("product");
<小时 />
你能做的是
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> objectMap = product.toMap();
<小时 />
在旧版本的 JSON-Java 上,不提供 toMap
方法,您可以做的是
final JSONObject product = item.getJSONObject("product");
final Map<String, Object> map =
product.keySet()
.stream()
.collect(Collectors.toMap(
Function.identity(),
product::get
));