在網站開發中經常遇到級聯資料的展示,比如選擇城市的時候彈出的省市縣選擇介面。很多前端製作人員習慣於從JSON中而不是從資料庫中擷取省市縣資料。那麼在選擇了省市縣中的某一個城市 ,儲存到資料庫中需要儲存所選城市的代碼。所以需要一個能將JSON資料(一般儲存在javascript指令碼中)結構全部匯入到資料庫中的功能。
JSON的特點是支援層級結構、支援數組表示的對象 。下面的樣本介紹如何將JSON的省市縣資料儲存到資料庫中,實現原理非常簡單,就是利用JSON的java工具包API,將階層的JSON對象數組通過遞迴的方式首選轉換為Java對象數組,然後儲存到資料庫中。
實現步驟是:
(一)首先定義一個JsonItem實體類:
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;
}
}
(二)定義一個工具類,在工具類中讀取Json資料檔案,並進行遞迴調用 :
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 ;
}
樣本資料(部分):
{
"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"
},