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

Implementation of JSON complex data processing: converting Json tree structure data to Java objects and storing them in the database

Jan 10, 2017 pm 12:57 PM

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;
}
}
Copy after login

(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 ;
}
Copy after login

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"
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

See all articles