Home >Web Front-end >JS Tutorial >Implementation of JSON complex data processing: converting Json tree structure data to Java objects and storing them in the database
In website development, we often encounter the display of cascading data, such as the province, city, and county selection interface that pops up when selecting a city. Many front-end developers are accustomed to obtaining province, city and county data from JSON instead of from the database. Then after selecting a city in a province, city or county, the code of the selected city needs to be stored in the database. Therefore, we need a function that can import the entire structure of JSON data (generally stored in javascript scripts) into the database.
The characteristic of JSON is that it supports hierarchical structures and objects represented by arrays. The following example introduces how to save JSON province, city and county data into the database. The implementation principle is very simple, which is to use the JSON Java toolkit API to convert the hierarchical JSON object array into a Java object array through recursion, and then Save to database.
The implementation steps are:
(1) First define a JsonItem entity class:
package org.openjweb.core.entity; public class JsonItem { private String sub_id; private String sub_name; private JsonItem[] items; public JsonItem[] getItems() { return items; } public void setItems(JsonItem[] items) { this.items = items; } public String getSub_id() { return sub_id; } public void setSub_id(String sub_id) { this.sub_id = sub_id; } public String getSub_name() { return sub_name; } public void setSub_name(String sub_name) { this.sub_name = sub_name; } }
(2) Define a tool class and read the Json data file in the tool class , and make recursive calls:
public static String importJson(String fullFileName,String jsonType,String encoding,HttpServletRequest request) throws Exception { //Json转换为实体类参考:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html String sReturn = ""; String jsonData = ""; try { jsonData = FileUtil.getTextFileContent(fullFileName, encoding); } catch(Exception ex) { sReturn ="读Json文件失败!"; } //获取rootId //logger.info(""); jsonData = jsonData.replace("\"items\":\"\"", ""); //去掉空的 items String parentId = jsonData.substring(jsonData.indexOf("\"id\":")+5); parentId = parentId.substring(0,parentId.indexOf(",")).trim(); parentId = parentId.replace("\"", ""); logger.info("root id=="+parentId); String parentName = jsonData.substring(jsonData.indexOf("\"name\":")+7); parentName = parentName.substring(0,parentName.indexOf(",")).trim(); parentName = parentName.replace("\"", ""); logger.info("root Name=="+parentName); String rootData = jsonData.substring(jsonData.indexOf("\"items\":")+8,jsonData.lastIndexOf("}")); rootData = jsonData.substring(jsonData.indexOf("[")+1,jsonData.lastIndexOf("]")); //不同json的id,name表示不一样,统一换成sub_id,subname以便与JsonItem的类属性匹配 // 替换后方便统一处理 rootData = rootData.replace("city_id", "sub_id"); rootData = rootData.replace("sub_city", "sub_name"); rootData = rootData.replace("city", "sub_name"); rootData = rootData.replace("sub_txt", "sub_name"); rootData = rootData.replace("sub_industry", "sub_name"); rootData = rootData.replace("industry_id", "sub_id"); rootData = rootData.replace("industry", "sub_name"); rootData = rootData.replace("sub_profession", "sub_name"); rootData = rootData.replace("profession_id", "sub_id"); rootData = rootData.replace("profession", "sub_name"); //将rootData转换为array rootData = "[" + rootData + "]"; try { FileUtil.str2file(rootData, "d:/jsonData.txt", "utf-8");//存储到磁盘检查字符串转换是否正确 } catch(Exception ex) { } JSONArray jsonArray = JSONArray.fromObject(rootData); Object[] os = jsonArray.toArray(); JsonItem[] items = (JsonItem[]) JSONArray.toArray(jsonArray, JsonItem.class); saveJsonEnt(jsonType,parentId,parentName,"-1",new Long(1)); dealJson(items,parentId,jsonType,new Long(1)); return sReturn ; } private static void saveJsonEnt (String jsonType,String jsonId,String jsonName,String parentId,Long levelId) throws Exception { logger.info(jsonType+"/"+jsonId+"/"+jsonName+"/"+parentId+"/"+String.valueOf(levelId)); CommJsonData ent = new CommJsonData(); ent.setJsonType(jsonType); ent.setJsonCode(jsonId); ent.setJsonName(jsonName); ent.setRowId(StringUtil.getUUID()); ent.setParentCode(parentId); ent.setLevelId(levelId); IDBSupportService service = (IDBSupportService)ServiceLocator.getBean("IDBSupportService3"); service.saveOrUpdate(ent); } private static String dealJson(JsonItem[] jsonItem,String parentId,String jsonType,Long level) { String sReturn = ""; if(jsonItem!=null&&jsonItem.length>0) { for(int i=0;i<jsonItem.length;i++) { JsonItem ent = jsonItem[i]; //System.out.println(ent.getSub_id()); //System.out.println(ent.getSub_name()); try { saveJsonEnt(jsonType,ent.getSub_id(),ent.getSub_name(),parentId,level+1); } catch(Exception ex) { ex.printStackTrace(); } if(ent.getItems()!=null) { //System.out.println("子项数:"+ent.getItems().length); dealJson(ent.getItems(),ent.getSub_id(),jsonType,level+1); } else { //System.out.println("没有子项!"); } } } //此函数 return sReturn ; }
Sample data (part):
{ "name": "全国", "id": "0000000000", "description": "崇德易城市数据", "modified": "2012年08月", "copyright": "http://www.chongdeyi.com/", "items": [ { "city": "北京市", "city_id": "1001000000", "items": [ { "sub_city":"东城区", "sub_id":"2001001000" }, { "sub_city":"西城区", "sub_id":"2001002000" }, { "sub_city":"朝阳区", "sub_id":"2001006000" }, { "sub_city":"丰台区", "sub_id":"2001007000" }, { "sub_city":"石景山区", "sub_id":"2001008000" }, { "sub_city":"海淀区", "sub_id":"2001009000" }, { "sub_city":"门头沟区", "sub_id":"2001010000" }, { "sub_city":"房山区", "sub_id":"2001011000" }, { "sub_city":"通州区", "sub_id":"2001012000" }, { "sub_city":"顺义区", "sub_id":"2001013000" }, { "sub_city":"昌平区", "sub_id":"2001014000" }, { "sub_city":"大兴区", "sub_id":"2001015000" }, { "sub_city":"怀柔区", "sub_id":"2001016000" }, { "sub_city":"平谷区", "sub_id":"2001017000" }, { "sub_city":"延庆县", "sub_id":"2001018000" }, { "sub_city":"密云县", "sub_id":"2001019000" }] },{ "city": "天津市", "city_id": "1002000000", "items": [ { "sub_city":"和平区", "sub_id":"2002001000" }
The above is the JSON complex data processing introduced by the editor to convert Json tree structure data to Java objects and Implementation of storing in database
For more related articles on the implementation of JSON complex data processing, Json tree structure data is converted into Java objects and stored in the database, please pay attention to the PHP Chinese website!