Search code examples
javajsonunirest

ClassCastException when trying to retrieve json node


I am receiving the following error when I try to store in a json response in a data store and then try to retrieve the particular json node from the response:

Error Message: java.lang.ClassCastException: java.lang.String cannot be cast to com.mashape.unirest.http.JsonNode

I can see it is retrieving the response as I wanted, but it errors out when retrieving the node in the next line.

    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 trying to parse and currently retrieved by httpResponse in the above code:

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

Solution

  • ClassCastException is thrown because in hitEndpoint method you are storing HttpResponse<String> to datastore so casting it to HttpResponse<JsonNode> in RetrieveExampleNode method is wrong!

    Instead you should have HttpResponse<JsonNode> in the first place:

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

    See more in Baeldung unirest guide

    If you need to convert between String and JsonNode use toString() method and JsonNode(String) constructor.