gpt4 book ai didi

html - 在 Java 中使用 Jsoup 将 HTML 表解析为 JSON

转载 作者:可可西里 更新时间:2023-11-01 12:59:29 25 4
gpt4 key购买 nike

我有一个格式如下的 HTML 表格:

<table>
<tbody>
<tr>
<td>Book1</td>
<td>Group1</td>
<td>Code1</td>
<td>Lesson1</td>
<td>Day1</td>
<td>Day2</td>
<td>Day3</td>
</tr>
<tr>
<td>Book2</td>
<td>Group2</td>
<td>Code2</td>
<td>Lesson2</td>
<td>Day1</td>
<td>Day2</td>
<td>Day3</td>
</tr>
</tbody>
</table>

我想用 Jsoup 解析这个 HTML,并输出一个格式如下的 JSON 字符串:

{
"Book1": {
"Group": "Group1",
"Code": "Code1",
"Lesson": "Lesson1",
"Day1": "Day1",
"Day2": "Day2",
"Day3": "Day3"
},
"Book2": {
"Group": "Group2",
"Code": "Code2",
"Lesson": "Lesson2",
"Day1": "Day1",
"Day2": "Day2",
"Day3": "Day3"
}
}

我试过这段代码:

public String TableToJson(String source) throws JSONException {
Document doc = Jsoup.parse(source);
JSONObject jsonObject = new JSONObject();
JSONArray list = new JSONArray();
for (Element table : doc.select("table")) {
for (Element row : table.select("tr")) {
Elements tds = row.select("td");
String Name = tds.get(0).text();
String Group = tds.get(1).text();
String Code = tds.get(2).text();

jsonObject.put("Name", Name);
jsonObject.put("Group", Group);
jsonObject.put("Code", Code);
list.put(jsonObject);
}
}
return list.toString();
}

但是返回了错误的结果:

[
{
"Name": "Book1",
"Group": "Group1",
"Code": "Code1"
},
{
"Name": "Book1",
"Group": "Group1",
"Code": "Code1"
}
]

我无法更改表格代码,因为它在另一台服务器上。

如何在 Java 中使用 Jsoup 从输入中获得所需的结果?

最佳答案

您的代码的问题是您正在尝试使用相同的 jsonObject 并且您还在使用不需要的 JsonArray。您需要一个包含 objects 但不是包含 array of objects

的对象
public String TableToJson(String source) throws JSONException {   
Document doc = Jsoup.parse(source);
JSONObject jsonParentObject = new JSONObject();
//JSONArray list = new JSONArray();
for (Element table : doc.select("table")) {
for (Element row : table.select("tr")) {
JSONObject jsonObject = new JSONObject();
Elements tds = row.select("td");
String Name = tds.get(0).text();
String Group = tds.get(1).text();
String Code = tds.get(2).text();
String Lesson = tds.get(3).text();
String Day1 = tds.get(4).text();
String Day2 = tds.get(5).text();
String Day3= tds.get(6).text();
jsonObject.put("Group", Group);
jsonObject.put("Code", Code);
jsonObject.put("Lesson", Lesson);
jsonObject.put("Day1", Day1);
jsonObject.put("Day2", Day2);
jsonObject.put("Day3", Day3);
jsonParentObject.put(Name,jsonObject);
}
}
return jsonParentObject.toString();
}

如果您需要说明,请告诉我!

关于html - 在 Java 中使用 Jsoup 将 HTML 表解析为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com