首页 > 解决方案 > 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
                            ));

标签: javaandroidjson

解决方案


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
               ));

推荐阅读