HTML,处理JSON响应 [英] Html, handling a JSON response
问题描述
我有一个页面作为HtmlUnit中的UnexpectedPage返回,响应为JSON.我可以使用HTMLUnit解析此消息还是需要其他库?
I have a page that comes back as an UnexpectedPage in HtmlUnit, the response is JSON. Can I use HTMLUnit to parse this or will I need an additional library?
推荐答案
HtmlUnit不支持它.它最多可以执行JS函数.您需要事先检查返回的响应的Content-Type
是否匹配application/json
,然后使用合适的工具进行解析. Google Gson 对此很有用.
HtmlUnit doesn't support it. It can at highest execute a JS function. You need to check beforehand if the Content-Type
of the returned response matches application/json
and then use the suitable tool to parse it. Google Gson is useful in this.
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将其转换为完全有价值的Javabean.您可以在此答案中找到示例.
If the JSON structure is known beforehand, you can even use Gson to convert it to a fullworthy Javabean. You can find an example in this answer.
这篇关于HTML,处理JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!