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

时间:2018-02-13 13:26:09

标签: java json gson jsoup

在我的程序中,我从连接的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-EventQueue-0”中的异常java.lang.ClassCastException:   com.google.gson.internal.LinkedTreeMap无法转换为   java.base / java.util.List的

如何显示details

1 个答案:

答案 0 :(得分:2)

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