Html,处理JSON响应

我有一个页面作为HtmlUnit中的UnexpectedPage返回,响应是JSON。 我可以使用HTMLUnit来解析这个吗?还是需要一个额外的库?

HtmlUnit不支持它。 它最高可以执行JSfunction。 您需要事先检查返回的响应的Content-Type是否与application/json匹配,然后使用合适的工具来解析它。 谷歌Gson在这方面很有用。

 WebClient client = new WebClient(); Page page = client.getPage("https://stackoverflow.com/users/flair/97901.json"); WebResponse response = page.getWebResponse(); if (response.getContentType().equals("application/json")) { String json = response.getContentAsString(); Map map = new Gson().fromJson(json, new TypeToken>() {}.getType()); System.out.println(map.get("displayName")); // Benju } 

如果事先知道JSON结构,您甚至可以使用Gson将其转换为完整的Javabean。 你可以在这个答案中找到一个例子。