<!-------------知识的力量是无限的(当然肯定还有更简单的方法)-----------!>
当我考虑将省市区三级联动数据从mysql转入mongodb时遇到了网上无直接插入mongodb的示例(基本均是mysql插入示例)。于是想到利用json文件直接导入mongodb会比较easy(SQLyog如何导出json?)
在SQLyog中写一个json格式查询语句:(省市区example如下:)看一下就能懂其中规则*
SELECT '{"code":"' AS a, cities.`cityid` AS b, '","name":"' AS c, cities.`city` AS d, '","provinceCode":"' AS e, cities.`provinceid` AS f, '"}' AS g FROM cities |
选取复制所有行到剪贴板:
接下来是将导出的json拼接成一个json文件:(在notpad++中以^查找来替换,拼接jsonarray串加array名(记得进行json校验与json压缩处理))
json在线校验URL:http://www.bejson.com/
json在线压缩URL:http://www.sojson.com/yasuo.html
最后以压缩成一个json文件的形式在java代码中解析
主干精华:
@Test public void testProCityArea(){ String fileName = "ProvCityArea.geojson"; String path = System.getProperty("user.dir") + "\\src\\main\\webapp\\static\\geojson\\" + fileName; JSONObject jsonobject = JSONObject.parseObject(FileHelper.readFile(path)); JSONArray provArray = jsonobject.getJSONArray("provinces"); for (Object object : provArray) { JSONObject provJson = (JSONObject) object; Province province = new Province(GuidUtils.getInstance().getGuid(), provJson.getString("code"), provJson.getString("name")); mongoTemplate.insert(province, "province"); } JSONArray cityArray = jsonobject.getJSONArray("city"); for (Object object : cityArray) { JSONObject cityJson = (JSONObject) object; City city = new City(GuidUtils.getInstance().getGuid(), cityJson.getString("code"), cityJson.getString("name"), cityJson.getString("provinceCode")); mongoTemplate.insert(city, "city"); } JSONArray areaArray = jsonobject.getJSONArray("area"); for (Object object : areaArray) { JSONObject areaJson = (JSONObject) object; Area area = new Area(GuidUtils.getInstance().getGuid(), areaJson.getString("code"), areaJson.getString("name"), areaJson.getString("cityCode")); mongoTemplate.insert(area, "area"); } }
|
FileHelper:
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader;
public class FileHelper {
public static String readFile(String path){ BufferedReader reader = null; String laststr = ""; try{ FileInputStream fileInputStream = new FileInputStream(path); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); reader = new BufferedReader(inputStreamReader); String tempString = null; while((tempString = reader.readLine()) != null){ laststr += tempString; } reader.close(); }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return laststr; }
}
|
GuidUtils
public class GuidUtils {
private static final GuidUtils instance = new GuidUtils();
private GuidUtils(){
}
public static GuidUtils getInstance() { return instance; }
public String getGuid() { UUID uuid = UUID.randomUUID(); String guid = uuid.toString(); guid = guid.replace("-", ""); return guid.toUpperCase(); }
}
|