gpt4 book ai didi

java - 如何使用 GSON 从 JSON 中提取字段

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

在我的程序中,我从连接的 URL 检索了 JSON,并希望获取错误详细信息。

这是我的代码:

private void result() throws IOException {
Result r = new Result();
String kb = "http://api.conceptnet.io/c/en/log-in";
Document docKb = Jsoup.connect(kb).get();
//content of the selected news article
String json = docKb.body().text();
Gson gson = new Gson();
Map<String, Object> asMap = gson.fromJson(json, Map.class);
List<Map<String, Object>> edges = (List)asMap.get("edges");
Map<String, Object> error = gson.fromJson(json, Map.class);
List<String> details = (List)error.get("error");
for (Map<String, Object> edge : edges) {
if (edge.containsKey("surfaceText") && edge.containsKey("weight")) {
String surfaceText = (String) edge.get("surfaceText");
//check if "surfaceText: null"
if (surfaceText == null) {
r.txtAreaNews.append("Surface Text: null \n");
r.txtAreaNews.append("Weight: " + edge.get("weight").toString());
} else {
r.txtAreaNews.append("Surface Text: " + edge.get("surfaceText").toString() + "\n");
r.txtAreaNews.append("Weight: " + edge.get("weight").toString());
}

}
r.txtAreaNews.append("\n");
}
for (String detail : details) {
if(detail.contains("details:"))
{
r.txtAreaNews.append(detail);
}
}
r.setVisible(true);
}

这是检索到的 JSON:

{
"@context": [
"http://api.conceptnet.io/ld/conceptnet5.5/context.ld.json",
"http://api.conceptnet.io/ld/conceptnet5.5/pagination.ld.json"
],
"@id": "/c/en/log-in",
"edges": [],
"error": {
"details": "'/c/en/log-in' is not a node in ConceptNet.",
"status": 404
}
}

我在 List<String> details = (List)error.get("error"); 处收到此错误行:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.base/java.util.List

如何获得 details要显示吗?

最佳答案

error 属性是一个子文档而不是数组...

"error": {
"details": "'/c/en/log-in' is not a node in ConceptNet.",
"status": 404
}

因此,它被反序列化为 HashMap,而不是 List

读取错误...

Map<String, Object> e = (Map) error.get("error")

e.get("details");
e.get("status");

如果传入的 JSON 包含...

"error": [
{
"details": "'/c/en/log-in' is not a node in ConceptNet.",
"status": 404
}
]

...(注意方括号)则 error 将是一个数组,因此将被反序列化为 List

关于java - 如何使用 GSON 从 JSON 中提取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767905/

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