首页 > 解决方案 > 尝试检索 json 节点时出现 ClassCastException

问题描述

当我尝试将 json 响应存储在数据存储中,然后尝试从响应中检索特定的 json 节点时,我收到以下错误:

错误消息:java.lang.ClassCastException:java.lang.String 无法转换为 com.mashape.unirest.http.JsonNode

我可以看到它正在检索我想要的响应,但是在检索下一行中的节点时出错。

    public void hitEndpoint(String endpoint) {
        DataStore dataStore = DataStoreFactory.getScenarioDataStore();
        HttpResponse<String> httpResponse;
        String url = "xxx/xxx";
        try {
            httpResponse = Unirest.post(url)
                    .asString();
            dataStore.put("httpResponse", httpResponse);
        ...

    }

    public void RetrieveExampleNode(String endpoint){
        DataStore dataStore = DataStoreFactory.getScenarioDataStore();
        HttpResponse<JsonNode> httpResponse = (HttpResponse<JsonNode>) dataStore.get("httpResponse");
        String getExampleNode = httpResponse.getBody().getObject().getJSONArray("test").getJSONObject(0).get("example").toString();
       //error in the above line
    }

JSON 试图解析并由上述代码中的 httpResponse 当前检索:

{"test": [{"example": "2019-09-18T04:32:12Z"}, {"type": "application/json","other": {"name": Test Tester}}]}

标签: javajsonunirest

解决方案


请检查 HttpResponse 类包并在获取 json 对象并在您的响应中获取数组之后转换 json 对象而不是数组:

     com.mashape.unirest.http.HttpResponse<JsonNode> response = Unirest.get("https://shopName.myshopify.com/admin/api/2019-04/orders.json").basicAuth("Api-Key", "Password").asJson();
   JSONObject myJSON = response.getBody().getObject();

我希望这对其他人也有帮助:)


推荐阅读