gpt4 book ai didi

java - 尝试检索 json 节点时出现 ClassCastException

转载 作者:行者123 更新时间:2023-12-02 00:35:08 25 4
gpt4 key购买 nike

当我尝试将 json 响应存储在数据存储中,然后尝试从响应中检索特定的 json 节点时,收到以下错误:

Error Message: java.lang.ClassCastException: java.lang.String cannot be cast to 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}}]}

最佳答案

抛出 ClassCastException 是因为 hitEndpoint您正在存储的方法HttpResponse<String>到数据存储,因此将其转换为 HttpResponse<JsonNode>RetrieveExampleNode方法不对!

相反,你应该有 HttpResponse<JsonNode>首先:

public void hitEndpoint(String endpoint) {
DataStore dataStore = DataStoreFactory.getScenarioDataStore();
HttpResponse<JsonNode> httpResponse;
String url = "xxx/xxx"t;
try {
httpResponse = Unirest.post(url)
.asJson();
dataStore.put("httpResponse", httpResponse);
...
}

查看更多Baeldung unirest guide

如果您需要在String之间进行转换和JsonNode使用toString()方法和JsonNode(String)构造函数。

关于java - 尝试检索 json 节点时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com