我有一个 HTML 表格,我想将其解析并转换为 JSON。
<table cellspacing="0" style="height: 24px;">
<tr class="tr-hover">
<th rowspan="15" scope="row">Network</th>
<td class="ttl"><a href="network-bands.php3">Technology</a></td>
<td class="nfo"><a href="#" class="link-network-detail collapse">GSM</a></td>
</tr>
<tr class="tr-toggle">
<td class="ttl"><a href="network-bands.php3">2G bands</a></td>
<td class="nfo">GSM 900 / 1800 - SIM 1 & SIM 2</td>
</tr>
<tr class="tr-toggle">
<td class="ttl"><a href="glossary.php3?term=gprs">GPRS</a></td>
<td class="nfo">Class 12</td>
</tr>
<tr class="tr-toggle">
<td class="ttl"><a href="glossary.php3?term=edge">EDGE</a></td>
<td class="nfo">Yes</td>
</tr>
</table>
在上表中
<th rowspan="15" scope="row">Network</th>
JSON 数组名称应为“Network”。
<td class="ttl"><a href="network-bands.php3">Technology</a></td>
Technology 是 Network 的副标题,因此它必须是 JSON 数组中的 JSON 元素。 Technology 数组中的值应该是来自
的值<td class="nfo"><a href="#" class="link-network-detail collapse">GSM</a></td>
我希望我的问题很清楚。我该怎么做?
最佳答案
final String HTML = "<table cellspacing=\"0\" style=\"height: 24px;\">\r\n<tr class=\"tr-hover\">\r\n<th rowspan=\"15\" scope=\"row\">Network</th>\r\n<td class=\"ttl\"><a href=\"network-bands.php3\">Technology</a></td>\r\n<td class=\"nfo\"><a href=\"#\" class=\"link-network-detail collapse\">GSM</a></td>\r\n</tr>\r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"network-bands.php3\">2G bands</a></td>\r\n<td class=\"nfo\">GSM 900 / 1800 - SIM 1 & SIM 2</td>\r\n</tr> \r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"glossary.php3?term=gprs\">GPRS</a></td>\r\n<td class=\"nfo\">Class 12</td>\r\n</tr> \r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"glossary.php3?term=edge\">EDGE</a></td>\r\n<td class=\"nfo\">Yes</td>\r\n</tr>\r\n</table>";
Document document = Jsoup.parse(HTML);
Element table = document.select("table").first();
String arrayName = table.select("th").first().text();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
Elements ttls = table.getElementsByClass("ttl");
Elements nfos = table.getElementsByClass("nfo");
JSONObject jo = new JSONObject();
for (int i = 0, l = ttls.size(); i < l; i++) {
String key = ttls.get(i).text();
String value = nfos.get(i).text();
jo.put(key, value);
}
jsonArr.put(jo);
jsonObj.put(arrayName, jsonArr);
System.out.println(jsonObj.toString());
输出(格式化):
{
"Network": [
{
"2G bands": "GSM 900 / 1800 - SIM 1 & SIM 2",
"Technology": "GSM",
"GPRS": "Class 12",
"EDGE": "Yes"
}
]
}
关于java - 从 HTML 表中提取数据并转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27560039/