在我的程序中,我从连接的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");行中得到了这个错误:
线程“AWT 0”中的异常java.lang.ClassCastException:不能将com.google.gson.internal.LinkedTreeMap转换为java.base/java.util.List
如何才能使details显示?
发布于 2018-02-13 13:32:25
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。
https://stackoverflow.com/questions/48767905
复制相似问题