Java:无法将JsonObject强制转换为Json数组

3
我使用get请求方法从API中获取数据。
 {"vulnerabilities":[{"id":5027994,"status":"open","closed_at":null,"created_at":"2019-06-07T06:10:15Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers":["adobe-reader-apsb09-15-cve-2009-2990"],"last_seen_time":"2019-07-24T05:00:00.000Z","fix_id":4953,"scanner_vulnerabilities":[{"port":null,"external_unique_id":"adobe-reader-apsb09-15-cve-2009-2990","open":true}],"asset_id":119920,"connectors":[{"name":"Nexpose Enterprise","id":7,"connector_definition_name":"Nexpose Enterprise","vendor":"R7"}],"service_ticket":null,"urls":{"asset":"dummy.com"},"patch":true,"patch_published_at":"2009-10-08T22:40:52.000Z","cve_id":"CVE-2009-2990","cve_description":"Array index error in Adobe Reader and Acrobat 9.x before 9.2, 8.x before 8.1.7, and possibly 7.x through 7.1.4 might allow attackers to execute arbitrary code via unspecified vectors.","cve_published_at":"2009-10-19T22:30:00.000Z","description":null,"solution":null,"wasc_id":null,"severity":9,"threat":9,"popular_target":false,"active_internet_breach":true,"easily_exploitable":true,"malware_exploitable":true,"predicted_exploitable":false,"custom_fields":[],"first_found_on":"2019-06-05T05:22:23Z","top_priority":true,"risk_meter_score":100,"closed":false}

但是在我的请求方法中,我收到了一个解析数据的错误,即我无法将一个jsonobject强制转换为jsonarray。

这是get请求方法:

public static void GetRequest() {

        BufferedReader reader;
        String access_token = "blahblahblah";       

        String line;
        StringBuffer responseContentReader = new StringBuffer();

        try {

            URL url = new URL("https://api.security.com/vulnerabilities/");
            connection = (HttpsURLConnection) url.openConnection();

            connection.setRequestProperty("X-Risk-Token ", access_token);


            connection.setRequestProperty("Accept", "application/json");

//here we should be able to "request" our setup
//Here will be the method I will use 
            connection.setRequestMethod("GET");

//after 5 sec if the connection is not successful time it out
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            int status = connection.getResponseCode();
//System.out.println(status); //here the connect was established  output was 200 (OK)

//here we are dealing with the connection isnt succesful

            if (status > 299) {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                while ((line = reader.readLine()) != null) {
                    responseContentReader.append(" ");
                    responseContentReader.append(line);
                    responseContentReader.append("\n");
                }
                reader.close();
//returns what is successful    
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    responseContentReader.append(" ");
                    responseContentReader.append(line);
                    responseContentReader.append("\n");
                }
                reader.close();
            }
            JsonParser parser = new JsonParser();
            Object object = parser.parse(responseContentReader.toString());
        JsonArray array = (JsonArray) object;  // here  is where the exception occurs
        for (int i = 0; i < array.size(); i++) {
            JsonArray jsonArray = (JsonArray) array.get(i);
            JsonObject jsonobj = (JsonObject) jsonArray.get(i);// cannot cast jsonobject to jsonarray
        }
        //JsonObject jsonObject = (JsonObject) object;
            System.out.println( responseContentReader.toString());



        } catch (MalformedURLException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO: handle exception
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }

    }

具体出现错误的地方在这里,说实话我不知道该怎么继续下去:

JsonParser parser = new JsonParser();
            Object object = parser.parse(responseContentReader.toString());
        JsonArray array = (JsonArray) object;  // here  is where the exception occurs
        for (int i = 0; i < array.size(); i++) {
            JsonArray jsonArray = (JsonArray) array.get(i);
            JsonObject jsonobj = (JsonObject) jsonArray.get(i);// cannot cast jsonobject to jsonarray
        }
        //JsonObject jsonObject = (JsonObject) object;
            System.out.println( responseContentReader.toString());

错误信息是:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray

1
你得到的数据不是一个数组。它是一个包含数组的 JSON 对象。 - Michael Albers
3个回答

1
您忘记使用括号和大括号来关闭您的JSON,应该像这样:

{"vulnerabilities":[{"id":5027994,"status":"open","closed_at":null,"created_at":"2019-06-07T06:10:15Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers":["adobe-reader-apsb09-15-cve-2009-2990"],"last_seen_time":"2019-07-24T05:00:00.000Z","fix_id":4953,"scanner_vulnerabilities":[{"port":null,"external_unique_id":"adobe-reader-apsb09-15-cve-2009-2990","open":true}],"asset_id":119920,"connectors":[{"name":"Nexpose Enterprise","id":7,"connector_definition_name":"Nexpose Enterprise","vendor":"R7"}],"service_ticket":null,"urls":{"asset":"dummy.com"},"patch":true,"patch_published_at":"2009-10-08T22:40:52.000Z","cve_id":"CVE-2009-2990","cve_description":"Array index error in Adobe Reader and Acrobat 9.x before 9.2, 8.x before 8.1.7, and possibly 7.x through 7.1.4 might allow attackers to execute arbitrary code via unspecified vectors.","cve_published_at":"2009-10-19T22:30:00.000Z","description":null,"solution":null,"wasc_id":null,"severity":9,"threat":9,"popular_target":false,"active_internet_breach":true,"easily_exploitable":true,"malware_exploitable":true,"predicted_exploitable":false,"custom_fields":[],"first_found_on":"2019-06-05T05:22:23Z","top_priority":true,"risk_meter_score":100,"closed":false}]}

尝试使用此json,应该可以正常工作!

我强烈建议您使用此网站格式化您的json https://jsonformatter.org/


我仍然收到一个错误:Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonObject 无法转换为 com.google.api.services.bigquery.model.JsonObject。 - xavier fuller

0

GET API返回的响应不是JsonArray,而是JsonObject

您可以将以下行进行更正-- JsonArray array = (JsonArray) object; 更改为 --

JsonObject jsonObject = (JsonObject) object;

此外,您可以通过以下方式读取其中的"vulnerabilities"--

JsonArray vulnerabilitiesArray = jsonObject.getJsonArray("vulnerabilities");


我仍然会收到一个错误:Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonObject 无法转换为 com.google.api.services.bigquery.model.JsonObject。 - xavier fuller
你能贴出完整的堆栈跟踪吗?看起来你正在使用不同类型的 JsonObject。请确保你正在使用 com.google.gson.JsonObject - Ameya Pandilwar

0

不要使用强制类型转换,而是像下面这样从对象或JSON响应中检索数组:

JsonObject object = ...
JsonArray array =  object.getJSONArray("vulnerabilities");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接