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

标签 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

最佳答案

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

关于java - 如何使用 toString() 方法和 JsonNode(String) 构造函数在 String 和 JsonNode 之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57985951/

相关文章:

ios - UNIRest:在异步 HTTP 响应上切换到新的 ViewController

java - 如何为我的模拟实例化 unirest HttpResponse<JsonNode> ?

java - 获取完整的 HTTP 请求

javascript - 如何使用 Unirest 在 Nodejs 中调用多个请求

java - java.mail 和套接字的问题

java - 使用 JPA 时构建器模式的最佳实践和实现

java - 为什么我的代码不返回 N 的最大值?

java - Mysql查询中答案为真、假

java - 生命周期配置未涵盖插件执行?

java.lang.NoClassDefFoundError : org/apache/http/concurrent/FutureCallback 错误