如何在String和JsonNode之间进行转换,请使用toString()方法和JsonNode(String)构造函数

时间:2019-09-18 05:58:36

标签: java unirest

我只需要编写一些指导以使我理解这个概念:

基本上,我需要在String和JsonNode之间进行转换,并且已经看到了说明要做什么的答案,但是作为新手开发人员,我不确定这意味着什么。如果我可以看到它已实施,那么它将有所帮助。

下面是我的响应的json节点:

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

}

下面,我尝试强制转换值,以便可以从json中检索值:

public void RetrieveExampleNode(String endpoint){
    DataStore dataStore = DataStoreFactory.getScenarioDataStore();
    JsonNode httpResponse = (JsonNode) dataStore.get("httpResponse");
    String getExampleNode = httpResponse.getBody().getObject().getJSONArray("test").getJSONObject(0).get("example").toString();
   //issue above is that it doesn't recognise getBody. When I remove getBody() and run the code, it still gives me a class cast exception error in the line where states JsonNode httpResponse = ...
}

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

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

我正在使用uniRest 1.4.9

1 个答案:

答案 0 :(得分:0)

下面的示例将JSON字符串转换为JSONObject

import org.json.JSONArray;
import org.json.JSONObject;

   String jsonString  = "{\"test\": [{\"example\": \"2019-09-18T04:32:12Z\"}, {\"type\": \"application/json\",\"other\": {\"name\": Test Tester}}]}";
        JSONObject jsonObject = new JSONObject(jsonString);

修改后的答案

//For Get using Unirest
        HttpResponse<JsonNode> httpResponse = Unirest.get("https://jsonplaceholder.typicode.com/posts/1").asJson();
        String responseString = httpResponse.getBody().toString();
        JSONObject object = new JSONObject(responseString); //Converting to JSONObject since it supports more functionalities
        System.out.println(object.keySet());


        //For Post using Unirest
        httpResponse = Unirest.post("https://jsonplaceholder.typicode.com/posts").body("This is sample Body").asJson();
        object = new JSONObject(responseString);
        System.out.println(object.keySet());