【问题标题】:Parse or convert HTML code embedded inside JSON object in the JSON response在 JSON 响应中解析或转换嵌入在 JSON 对象中的 HTML 代码
【发布时间】:2020-06-14 02:52:52
【问题描述】:

我有以下网址:

https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=The%20Matrix

返回 JSON 响应,其中 HTML 代码 嵌入在 JSON 对象 中(查看链接)。

我如何使用 java 从该 HTML 部分检索详细信息,例如演员、导演等?

如果可能的话,如何使用 java 将该 Html 部分转换为 JSON?

或者有什么方法可以改变 url 本身以获取可读的 JSON 格式的电影数据?

【问题讨论】:

  • 你能在嵌入式中提供演员/导演的选择器吗?我找不到那些字符串
  • 你的意思是对应的标签名称吗? @Dhrubajyoti
  • 是的,演员/导演在嵌入的 html 中出现在哪里?
  • 主演导演
  • 我其实是把html部分单独复制到了一个文件中,保存为html,在浏览器中查看就可以看到标签了..

标签: java json rest web-services


【解决方案1】:

这是一个使用jsoup解析HTML和jackson解析JSON的解决方案:

public static void main(String[] args) throws IOException {
    // Extract JSON string
    String body = Jsoup.connect("https://en.wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=The%20Matrix")
    .ignoreContentType(true).execute().body();
    // Extract HTML string from JSON
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    JsonNode targetNode = mapper.readTree(body).get("parse").get("text").get("*");
    // Generic but fragile function to extract specific details
    Function<String, String> retrieveDetailsOf = detailsOf ->
        Jsoup.parse(targetNode.asText())
                .select(".infobox tr th:contains(" + detailsOf + ") ~ td a[title]")
                .stream().map(e -> e.attr("title")).collect(Collectors.toList()).toString();

    System.out.println(retrieveDetailsOf.apply("Directed by"));
    System.out.println(retrieveDetailsOf.apply("Produced by"));
    System.out.println(retrieveDetailsOf.apply("Music by"));
    System.out.println(retrieveDetailsOf.apply("Starring"));
}

输出:

[The Wachowskis]
[Keanu Reeves, Laurence Fishburne, Carrie-Anne Moss, Hugo Weaving, Joe Pantoliano]

依赖关系:

implementation("org.jsoup:jsoup:1.12.2")
implementation("com.fasterxml.jackson.core:jackson-core:2.10.2")
implementation("com.fasterxml.jackson.core:jackson-databind:2.10.2")

请注意,内容结构的任何更改都会导致中断。如果可用,请使用官方电影详细信息 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多