首页 > 解决方案 > 如何在 String 和 JsonNode 之间转换使用 toString() 方法和 JsonNode(String) 构造函数

问题描述

我只需要一些指导来写这篇文章,以便我理解这个概念:

基本上我需要在 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

标签: javaunirest

解决方案


下面的示例是将 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());

推荐阅读