java将html转json
时间: 2023-07-29 16:11:36 浏览: 201
要将HTML转换为JSON,您需要使用一些库。以下是一些步骤:
1.使用 Jsoup 库解析 HTML。
2.将 Jsoup 的 Document 对象转换为 JSON 对象。您可以使用 JSON-lib 或 Gson 等库来完成此任务。
以下是一个使用 Gson 库的示例代码:
```java
import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class HtmlToJson {
public static void main(String[] args) {
String html = "<html><head><title>Example</title></head><body><h1>Hello, World!</h1></body></html>";
// 使用 Jsoup 解析 HTML
Document doc = Jsoup.parse(html);
// 将 Jsoup 的 Document 对象转换为 JSON 对象
Gson gson = new Gson();
String json = gson.toJson(doc);
System.out.println(json);
}
}
```
输出结果:
```
{
"childNodeSize": 2,
"baseUri": "",
"childNodes": [
{
"nodeName": "#comment",
"attributes": {},
"val": "!doctype html"
},
{
"nodeName": "html",
"attributes": {},
"childNodes": [
{
"nodeName": "head",
"attributes": {},
"childNodes": [
{
"nodeName": "title",
"attributes": {},
"childNodes": [
{
"nodeName": "#text",
"attributes": {},
"val": "Example"
}
]
}
]
},
{
"nodeName": "body",
"attributes": {},
"childNodes": [
{
"nodeName": "h1",
"attributes": {},
"childNodes": [
{
"nodeName": "#text",
"attributes": {},
"val": "Hello, World!"
}
]
}
]
}
]
}
],
"ownerDocument": {
"childNodeSize": 2,
"baseUri": "",
"childNodes": [
{
"nodeName": "#comment",
"attributes": {},
"val": "!doctype html"
},
{
"nodeName": "html",
"attributes": {},
"childNodes": [
{
"nodeName": "head",
"attributes": {},
"childNodes": [
{
"nodeName": "title",
"attributes": {},
"childNodes": [
{
"nodeName": "#text",
"attributes": {},
"val": "Example"
}
]
}
]
},
{
"nodeName": "body",
"attributes": {},
"childNodes": [
{
"nodeName": "h1",
"attributes": {},
"childNodes": [
{
"nodeName": "#text",
"attributes": {},
"val": "Hello, World!"
}
]
}
]
}
]
}
],
"ownerDocument": null,
"nodeName": "#root",
"attributes": {},
"val": ""
},
"nodeName": "#root",
"attributes": {},
"val": ""
}
```
阅读全文