java - 如何在 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
解决方案
下面的示例是将 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());
推荐阅读
- uwp - 如何在 HockeyApp 上将电子邮件附加到崩溃日志
- javascript - Javascript Object.create:设置数据时内存会发生什么?
- java - Confluent Cloud 上的 Kafka 流:值为“600000”的“segment.ms”超出内部重新分区主题的最小限制 14400000
- google-api - 通过谷歌开发者控制台项目ID找出使用的电子邮件帐户
- arrays - 在scala中查找给定数组的最小值和最大值
- postgresql - 如何在非英语语言中使用 GraphQL 枚举?后记
- bash - 如何找到 bash 文件的位置?
- .net - PowerShell 中的进程、实例和运行空间
- jelastic - 无法登录 Jelastic intellij 插件
- javascript - 将数组的值从一个函数实例化为jquery中的另一个函数