我从HTTPGET
方法获得 HTML 响应。如何解析 html 对JSON的响应?
我用哪种API来解析它?
我也想知道x-path
的主要用途是什么。
HTML响应:
<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />
答案 0 :(得分:0)
您可以使用jsoup作为将HTML转换为JSON的工具。
final String HTML = "<!DOCTYPE html> <[if IE 8]> <html lang="en" class="ie ie8 lt-ie9 lt-ie10"> <![endif]> <[if IE 9]> <html lang="en" class="ie ie9 lt-ie10"> <![endif]> <if IE]> <html lang="en" class="ie"> <![endif] <[if gt IE 9]> <html lang="en"> <![endif] <head prefix="og: ogp.me/ns# fb: ogp.me/ns/fb# snapdeallog:#"> <link rel="dns-prefetch" href="i1.sdlcdn.com"; />";
Document document = Jsoup.parse(HTML);
Element element = document.select("ANY HTML TAG").first();
String arrayName = element.select("TAG2").first().text();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
Elements ie = element.getElementsByClass("ie");
Elements ei9 = element.getElementsByClass("ei9");
JSONObject jobj = new JSONObject();
for (int i = 0, l = ie.size(); i < l; i++) {
String key = ie.get(i).text();
String value = ei9.get(i).text();
jobj.put(key, value);
}
jsonArr.put(jobj);
jsonObj.put(arrayName, jsonArr);
System.out.println(jsonObj.toString());