java - 尝试检索 json 节点时出现 ClassCastException
问题描述
当我尝试将 json 响应存储在数据存储中,然后尝试从响应中检索特定的 json 节点时,我收到以下错误:
错误消息:java.lang.ClassCastException:java.lang.String 无法转换为 com.mashape.unirest.http.JsonNode
我可以看到它正在检索我想要的响应,但是在检索下一行中的节点时出错。
public void hitEndpoint(String endpoint) {
DataStore dataStore = DataStoreFactory.getScenarioDataStore();
HttpResponse<String> httpResponse;
String url = "xxx/xxx";
try {
httpResponse = Unirest.post(url)
.asString();
dataStore.put("httpResponse", httpResponse);
...
}
public void RetrieveExampleNode(String endpoint){
DataStore dataStore = DataStoreFactory.getScenarioDataStore();
HttpResponse<JsonNode> httpResponse = (HttpResponse<JsonNode>) dataStore.get("httpResponse");
String getExampleNode = httpResponse.getBody().getObject().getJSONArray("test").getJSONObject(0).get("example").toString();
//error in the above line
}
JSON 试图解析并由上述代码中的 httpResponse 当前检索:
{"test": [{"example": "2019-09-18T04:32:12Z"}, {"type": "application/json","other": {"name": Test Tester}}]}
解决方案
请检查 HttpResponse 类包并在获取 json 对象并在您的响应中获取数组之后转换 json 对象而不是数组:
com.mashape.unirest.http.HttpResponse<JsonNode> response = Unirest.get("https://shopName.myshopify.com/admin/api/2019-04/orders.json").basicAuth("Api-Key", "Password").asJson();
JSONObject myJSON = response.getBody().getObject();
我希望这对其他人也有帮助:)
推荐阅读
- javascript - 如何在 ReactJs 样式中有条件地调用不同的类名
- sql - 在 Hana 中使用 with 子句创建表
- python - TypeError:只能将str(不是“numpy.int64”)连接到str
- javascript - 在数组中查找字符串
- c# - 在 ASP.NET Core 2.2 中使用 InProcess 托管模型时,Serilog 不会将日志写入文件
- symfony - 实体值不持久(Doctrine - Symfony 4.1)
- python - 从 temp_pb2.py 文件生成 temp.proto 文件
- javascript - 如何更改 URL.createObjectURL 下载名称?
- angularjs - Angular 2+(Angular 7)是否有代码差异组件
- json - 如何在 Golang 中创建字典列表?