json转html
{
"DS": [
{
"PROVINCE": "陕西省",
"ADMIN_CODE_CHN": "610600",
"STATION_ID_C": "53845",
"LON": "109.4497",
"V31001_S": 10,
"V31001_X": 0
},
{
"PROVINCE": "陕西省",
"ADMIN_CODE_CHN": "610600",
"STATION_ID_C": "53845",
"LON": "109.4497",
"V31001_S": 10,
"V31001_X": 0
}
]
}
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
public static String jsonObject2Html(JSONObject jsonObject) {
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 8px;}</style>");
htmlBuilder.append("<table>");
JSONArray jsonArray = jsonObject.getJSONArray("DS");
JSONObject firstObject = jsonArray.getJSONObject(0);
// 创建表头
htmlBuilder.append("<tr>");
for (String key : firstObject.keySet()) {
htmlBuilder.append("<th>").append(key).append("</th>");
}
htmlBuilder.append("</tr>");
// 添加数据行
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject dataObject = jsonArray.getJSONObject(i);
htmlBuilder.append("<tr>");
for (String key : dataObject.keySet()) {
htmlBuilder.append("<td>").append(dataObject.get(key)).append("</td>");
}
htmlBuilder.append("</tr>");
}
htmlBuilder.append("</table>");
return htmlBuilder.toString();
}
<style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 8px;}</style>
<table>
<tr><th>PROVINCE</th><th>ADMIN_CODE_CHN</th><th>STATION_ID_C</th><th>LON</th><th>V31001_S</th><th>V31001_X</th></tr>
<tr><td>陕西省</td><td>610600</td><td>53845</td><td>109.4497</td><td>10</td><td>0</td></tr>
</table>