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

How to convert between String and JsonNode use toString() method and JsonNode(String) constructor

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

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

下面的例子是将 JSON 字符串转换为 JSON 对象

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());