【问题标题】:Java : Not Able to cast jsonobject to Json arrayJava:无法将 jsonobject 转换为 Json 数组
【发布时间】:2019-08-11 23:02:08
【问题描述】:

我能够使用我的 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

【问题讨论】:

  • 返回的数据不是数组。它是一个包含数组的 json 对象。

标签: java arrays json httpresponse


【解决方案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,它应该可以工作!

我强烈推荐你使用这个网站来格式化你的 jsons https://jsonformatter.org/

【讨论】:

  • 我仍然在线程“main”java.lang.ClassCastException 中收到错误异常:com.google.gson.JsonObject 无法转换为 com.google.api.services.bigquery.model.JsonObject
【解决方案2】:

不是强制转换,而是从对象或 json 响应中检索数组,如下所示:

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

【讨论】:

    【解决方案3】:

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

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

    JsonObject jsonObject = (JsonObject) object;

    此外,您可以通过 --

    阅读 "vulnerabilities"

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

    【讨论】:

    • 我仍然在线程“main”java.lang.ClassCastException 中收到错误异常:com.google.gson.JsonObject 无法转换为 com.google.api.services.bigquery.model.JsonObject
    • 你能发布整个堆栈跟踪吗?似乎您正在使用不同类型的JsonObject。确保您使用的是com.google.gson.JsonObject
    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多