JSON tree structure data of complex data processing to the Java object and stored in the database implementation _java

Source: Internet
Author: User

In the development of the site often encounter cascading data display, such as the choice of cities when the city of the provinces and counties to choose the interface. Many front-end producers are accustomed to getting provincial and county data from JSON rather than from a database. Then in the choice of cities and counties in a city, stored in the database needs to store the selected city code. So you need an ability to import JSON data (typically stored in JavaScript scripts) into the database.

JSON is characterized by support for hierarchies, objects that support array representations. The following example describes how to save the city and county data of JSON to a database in a very simple way: by using the JSON Java Toolkit API, the hierarchical JSON object array is preferred to be converted to a Java object array recursively, and then saved to the database.

The implementation steps are:

(i) 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;
}
}

(b) Define a tool class, read the JSON data file in the tool class, and make a recursive call:

public static string Importjson (String fullfilename,string jsontype,string encoding,httpservletrequest request) throws
Exception {//json conversion to entity class Reference: 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 = "failed to read JSON file!";}
Obtain Rootid//logger.info (""); Jsondata = Jsondata.replace ("\" items\ ": \" "", "");
Remove the empty 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 ("]")); Different JSON id,name representations are not the same, unified replaced by Sub_id,subname in order to match//replace the Jsonitem class attributes 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");
Convert Rootdata to array rootdata = "[+ Rootdata +]"; try {fileutil.str2file (rootdata, "D:/jsondata.txt", "utf-8");//Save to disk check string conversion is correct} catch (Exception ex) {} Jsonarray JSON
Array = 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 Exce
ption {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 ("Number of subkeys:" +ent.getitems (). length);
Dealjson (Ent.getitems (), ent.getsub_id (), jsontype,level+1);
else {//system.out.println ("no subkeys!");}
}//This function return Sreturn;  }

Sample data (partial):

{"Name": "National", "id": "0000000000", "description": "Chong Tak Yi City Data", "Modified": "August 2012", "Copyright": "Http://www.chongdeyi . com/"," items ": [{" City ":" Beijing "," city_id ":" 1001000000 "," items ": [{" sub_city ":" Dongcheng District "," sub_id ":" 2001001000 "}, {" Su B_city ":" Xicheng District "," sub_id ":" 2001002000 "}, {" Sub_city ":" Chaoyang District "," sub_id ":" 2001006000 "}, {" Sub_city ":" Fengtai District "," sub_id ":" 2001007000 "}, {" Sub_city ":" Shijingshan District "," sub_id ":" 2001008000 "}, {" Sub_city ":" Haidian "," sub_id ":" 2001009000 "}, {" Sub_city ":" Door
Head ditch area "," sub_id ":" 2001010000 "}, {" Sub_city ":" Fangshan District "," sub_id ":" 2001011000 "}, {" Sub_city ":" Tongzhou District "," sub_id ":" 2001012000 "}, {"sub_city": "Shunyi District", "sub_id": "2001013000"}, {"Sub_city": "Changping District", "sub_id": "2001014000"}, {"Sub_city": "Daxing District", "sub_id": " 2001015000 "}, {" Sub_city ":" Huairou "," sub_id ":" 2001016000 "}, {" Sub_city ":" Pinggu District "," sub_id ":" 2001017000 "}, {" Sub_city ":" Yanqing County "," sub_id ":" 2001018000 "}, {" Sub_city ":" Miyun "," sub_id ":" 2001019000 "}]},{" City ":" Tianjin "," city_id ":" 1002000000 "," ite " MS ": [{" sub_city ":" Zone of Peace "," sub_id ":"2002001000 "} 

The above is described in the JSON complex data processing of JSON tree structure data to Java objects and stored in the database implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.