I have an HTML table that is formatted like this:
<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>
I would like to parse this HTML with Jsoup, and output a JSON string formatted like this:
{
"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"
}
}
I tried this code:
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();
}
But it returned the wrong result:
[
{
"Name": "Book1",
"Group": "Group1",
"Code": "Code1"
},
{
"Name": "Book1",
"Group": "Group1",
"Code": "Code1"
}
]
I can't change table code because it's on another server.
How can I get the desired result from the input using Jsoup in Java?
JSONObject.