search
HomeWeb Front-endJS TutorialImplementation 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!

Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

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.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

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.

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),