Java实现省市区数据Json格式的转换
问题背景
某天同事给我一份省市区行政规划编码的excel数据,让我整理成对应的一定规则的json格式。原excel数据格式如下,原数据大概2400行左右,这里实例给出50行。
|
要求严格整理成如下json格式:
别人gitHub上js实现过的json格式转换
由于自己目前还不熟悉js代码,所以决定来用Java来实现下。
以下是实现思路和步骤:
1、将excel数据读取到MySQL数据库
这里我使用的navicat操作的,先将excel改为csv格式,然后导入到本地MySQL中:
2、创建数据库的连接和释放
package Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connect {
//都除掉了static修饰
public Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pwd = "root";
Connection connection = DriverManager.getConnection(url, user, pwd);
return connection;
}
public void relase(Connection connection, Statement statement, ResultSet resultSet) throws Exception {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
3、读取数据分别封装到省、市、区集合list中
1、创建DataObjects,用几个list来装载省市区数据,具体逻辑看代码,写的比较简单,还不规范:
package domain;
import java.util.ArrayList;
import java.util.List;
public class DataObjects {
private int districtNumber;
private String districtName;
private int parentDistrictNumber;
private String parentDistrictName;
public DataObjects() {
}
public DataObjects(int districtNumber, String districtName, int parentDistrictNumber, String parentDistrictName) {
this.districtNumber = districtNumber;
this.districtName = districtName;
this.parentDistrictNumber = parentDistrictNumber;
this.parentDistrictName = parentDistrictName;
}
public int getDistrictNumber() {
return districtNumber;
}
public void setDistrictNumber(int districtNumber) {
this.districtNumber = districtNumber;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public int getParentDistrictNumber() {
return parentDistrictNumber;
}
public void setParentDistrictNumber(int parentDistrictNumber) {
this.parentDistrictNumber = parentDistrictNumber;
}
public String getParentDistrictName() {
return parentDistrictName;
}
public void setParentDistrictName(Stri