org.json.JSONObject无法转换为java.util.Map

时间:2019-03-29 22:09:29

标签: java android json

将地图投射到Android应用程序的JSONObject。生成但在运行时崩溃。在Logcat中查看并得到错误:

  

org.json.JSONObject无法转换为java.util.Map

以下是相关部分:

JSONObject item = new JSONObject(data);
Map product = ((Map)item.get("product"));

具体是导致崩溃的第二行。我注释掉了代码,直到取消注释此行导致崩溃为止。

链接到的JSON是Select-Object

取消映射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
                            ));

1 个答案:

答案 0 :(得分:1)

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