从HTML表中提取数据并转换为JSON

Mil*_*ler 3 java arrays json

我有一个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>
Run Code Online (Sandbox Code Playgroud)

在上表中

<th rowspan="15" scope="row">Network</th> 
Run Code Online (Sandbox Code Playgroud)

JSON数组名称应为"网络".

<td class="ttl"><a href="network-bands.php3">Technology</a></td>
Run Code Online (Sandbox Code Playgroud)

技术是网络的子标题,因此它必须是JSON数组中的JSON元素.Technology数组中的值应该是来自的值

<td class="nfo"><a href="#" class="link-network-detail collapse">GSM</a></td>
Run Code Online (Sandbox Code Playgroud)

我希望我的问题很明确.我怎样才能做到这一点?

Jar*_*ler 6

以下是使用JsoupJSON作为依赖关系的答案:

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());
Run Code Online (Sandbox Code Playgroud)

输出(格式化):

{
    "Network": [
        {
            "2G bands": "GSM 900 / 1800 - SIM 1 & SIM 2",
            "Technology": "GSM",
            "GPRS": "Class 12",
            "EDGE": "Yes"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)