9
我有一個頁面在HtmlUnit中作爲UnexpectedPage返回,響應是JSON。我可以使用HTMLUnit來解析這個問題,還是需要額外的庫?Html,處理JSON響應
我有一個頁面在HtmlUnit中作爲UnexpectedPage返回,響應是JSON。我可以使用HTMLUnit來解析這個問題,還是需要額外的庫?Html,處理JSON響應
HtmlUnit不支持它。它可以在最高執行一個JS函數。您需要事先檢查返回響應的Content-Type
是否與application/json
匹配,然後使用合適的工具解析它。 Google 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<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
System.out.println(map.get("displayName")); // Benju
}
如果JSON結構是事先知道,你甚至可以用GSON將其轉換爲一個fullworthy的Javabean。你可以在this answer找到一個例子。