如何使用jsoup从HTML获取JSON数据

时间:2019-05-10 07:54:57

标签: java android json android-webview jsoup

我在WebView中命中了一个URL,该URL以HTML格式返回响应。我试图使用Jsoup从该HTML获取JSON数据,但无法获取。

我正在获取以下格式的数据:

<pre style="word-wrap: break-word; white-space: pre-wrap;">{"status":"success","connected_id":"dfdffdffdfdfdf"}</pre>

现在我想从上述回复中获得该connected_id,但我无法获得。

代码:

Document document = Jsoup.parse(html);
Elements elements = document.select("pre");
Log.d("TAG", " myHTMLResponseCallback1 : " + elements.attr("pre"));

我在elements.attr("connected_id")中没有任何价值。

2 个答案:

答案 0 :(得分:1)

使用jsoup从html检索json数据的最好方法是通过data()方法提取json:

Document document = Jsoup.parse(html);
Element element = document.selectFirst("pre#id");
String jsonText = element .data();

答案 1 :(得分:0)

因此,这里的问题是您的1c0143c6ac7505c8866d10270a480dec 元素包含JSON字符串,无法使用Jsoup对其进行解析。无论如何,第一步是提取JSON字符串:

<pre>

从JSON字符串提取String html = "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\"status\":\"success\",\"connected_id\":\"dfdffdffdfdfdf\"}</pre>"; Document document = Jsoup.parse(html); Element element = document.selectFirst("pre"); String json = element.text(); 的最简单但可能不是最好的方法是使用正则表达式:

connected_id

更好的方法是解析JSON字符串。您可以使用JacksonGsonothers之类的JSON解析库来实现此目的。

以下是使用杰克逊的示例:

Pattern pattern = Pattern.compile("\"connected_id\":\"(?<id>.*)\"");
Matcher matcher = pattern.matcher(json);
if (matcher.find()) {
    String connectedId = matcher.group("id");
    // ...
}

如果要提取更多值(不仅是ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(json); String connectedId = jsonNode.get("connected_id").asText(); ),建议将JSON字符串转换为Java对象,如下所示:

connected_id

您现在可以使用此类读取json值:

public class MyObject {
    private String status;
    @JsonProperty("connected_id")
    private String connectedId;
    // more attributes if you need them

    // getter and setter
}

所有解决方案都将返回ObjectMapper mapper = new ObjectMapper(); MyObject result = mapper.readValue(json, MyObject.class); String connectedId = result.getConnectedId(); 作为结果。