JSON turn JavaBean

Source: Internet
Author: User

In the network, we often see some of the jar packages that are automatically converted to JavaBean by JSON, and the people in the project group are using it, and a little research is done by reflection. I carefully think of the logic inside, I think the direct generation of JavaBean code is not more direct, reflected in the mobile side, how to say that all are consumption of resources.

Structure of the Java Bean class

The first thing to comb down, exactly what the Bean class is a file, very simple is a lot of attributes of the class file, attributes have many categories, but from the JSON point of view, the category is limited: The basic type and list. We can use Python to simulate the following:

# encoding:utf-8 ' Created on 2014.12.24@author:13051041 ' class Javaclass (object): ' Class Templete ' d        EF __init__ (self, name): ' Constructor ' self.mname = name; Self.mintegerlist = [] Self.mstrlist = [] Self.mbollist = [] Self.mlistlist = [] Self.mclassli st = [] self.minclasstypelist = [] self.misparcelable = True self.mpackagename = "Package Com.codegen        Erator; "        def addintattribute (self, str1): ' Add String attribute ' Self.mIntegerList.append (str1) def addunicodeattribute (self, str1): "' Add String attribute ' Self.mStrList.append (s TR1) def addbooleanattribute (self, BOL): ' Add Boolean attribute ' SELF.MB        Ollist.append (BOL) def addlistattribute (self, List1): "' Add List attribute ' Self.mListList.append (List1)                 def addclassattribute (self, CLS): "' Add Class attribute ' Self.mclasslist        . Append (CLS) def addinclasstype (self, Inclass): "' Add Inner Class attribute ' Self.mInClassTypeList.append (inclass) def test (self): print "-----This is Javaclass information sta RT-----"Print" class ' s name is%s "% self.mname print" class ' s integer is%s "% self.mintegerlist P Rint "class ' s String is%s"% self.mstrlist print "class ' s Boolean is%s"% self.mbollist print "class ' s L  Ist is%s "% self.mlistlist print" class ' s inner class is%s "% self.mclasslist print" class ' s inner class Type is%s '% self.minclasstypelist print '-----This is javaclass information end-----"classnum = 0 def autogen Eratorclassname (): global Classnum Classnum = classnum + 1 return "class%d"% classnumdef Buildjavaclassnode (JSON Object, ClassName): JAvaclass = Javaclass (className) keys = Jsonobject.keys () for key in Keys:t = Type (Jsonobject[key]) if         t = = Int:javaclass.addIntAttribute (key) If t = = Unicode:javaclass.addUnicodeAttribute (key) If T = = Bool:javaclass.addBooleanAttribute (key) If t = = Dict:newclassname = Autogen Eratorclassname () Javaclass.addclassattribute ((Newclassname, key)) Javaclass.addinclasstype (buildJa  Vaclassnode (Jsonobject[key], newclassname)) if T = = List:t2 = Type (jsonobject[key][0]) if T2  = = Dict:newclassname = Autogeneratorclassname () javaclass.addlistattribute (Newclassname,                Key) Javaclass.addinclasstype (Buildjavaclassnode (jsonobject[key][0], newclassname)) Else: Javaclass.addlistattribute ((T2, key)) return Javaclass

  

Generate Java files, recursion is the kingly

We have a Python class called Javaclass, which reads JSON in Python and generates the instance directly. Now the task is to write this instance into the file. Consider the nested relationship of class, and the best way to generate it is recursion:

# encoding:utf-8 ' Created on 2014.12.26@author:13051041 ' class_import = '%simport java.util.arraylist;import Java.util.list;import Org.json.jsonarray;import Org.json.jsonobject;import org.json.JSONException; class_import_parcelable = "' Import android.os.parcel;import android.os.Parcelable; Class_head = "Public%s class%s {" ' class_head_parcelable = ' Public%s class%s implements parcelable{public%s (    {} public%s (Parcel in) {Readfromparcel (in); } ' class_method_end = '}\n ' attribute_temp = ' public%s%s;\n ' Method_analyzer = ' public void Analyzerjson (Jsonobje        CT jsonobject) throws jsonexception {if (jsonobject = = null) {return; } ' Method_temp = ' public%s%s (%s) throws jsonexception {\ n ' method_get_int = ' '%s = Getjsonattributeutil.getint ( Jsonobject, "%s"); method_get_string = '%s = getjsonattributeutil.getstring (jsonobject, '%s '); Method_get_boolean = '%s = Getjsonattributeutil.getboolean (Jsonobject, "%s");‘‘‘                      Method_get_class = '%s ' = new%s (); %s.analyzerjson (Getjsonattributeutil.getjsonobject (Jsonobject, "%s"));    Method_get_list = "%s= new arraylist<%s> ();    Jsonarray array%s = Getjsonattributeutil.getjsonarray (Jsonobject, "%s");    int%slen = Array%s.length ();         for (int i = 0;i<%slen;i++) {%s item = new%s ();         Item.analyzerjson (Array%s.getjsonobject (i));    %s.add (item); } ' Method_parcelable_write = ' public void Writetoparcel (Parcel dest, int flags) {\ n ' ' Mehtod_parcelable_value_write = "dest.write%s (%s); \ n" method_parcelable_read = "public void Readfromparcel (Parcel in) {\ n" "Mehtod_parcelable_  Value_read = "%s= in.readstring (); "is_parcelable = Truefile_name =" Bean "Def writeparcelabelmethod (F, JCLs): # Writetoparcel Method F.write (Method_par celable_write) for attribute in Jcls.mintegerlist:f.write ("Dest.writeint (%s); \ n"% (attribute)) for attribut E in Jcls.mstrlist:f.write ("Dest.writeString (%s); \ n "% (attribute)) for attribute in Jcls.mbollist:f.write (" Dest.writebyte ((Byte) (%s? 1:0)); \ n "% (attribute)) for attribute in Jcls.mlistlist:f.write (" Dest.writetypedlist (%s); "% (at TRIBUTE[1]))) for attribute in Jcls.mclasslist:f.write ("Dest.writeparcelable (%s, parcelable_write_re turn_value); "% attribute[1]) F.write (class_method_end) # Readfromparcel Method F.write (metho D_parcelable_read) for attribute in Jcls.mintegerlist:f.write ("%s= in.readint (); \ n"% (attribute)) for Attri Bute in Jcls.mstrlist:f.write ("%s= in.readstring (); \ n"% (attribute)) for attribute in Jcls.mbollist:f. Write ("%s = In.readbyte ()! = 0;\n"% (attribute)) for attribute in Jcls.mlistlist:f.write ("%s = new Arrayli St<%s> (); "% (Attribute[1], attribute[0])) F.write (" In.readtypedlist (%s,%s.creator); "% (attribute[1], Attri BUTE[0])) for attributE in Jcls.mclasslist:f.write ("%s = in.readparcelable (%s.class.getclassloader ());"% (Attribute[1], attribute[0]))  F.write (class_method_end) # describecontents Method f.write ("public int describecontents () {return        0;} ") F.write ("public static final parcelable.creator<%s> Creator = new parcelable.creator<            %s> () {public%s createfromparcel (Parcel.) {return new%s (in);            } public%s[] NewArray (int size) {return new%s[size];        }        };    "% (Jcls.mname, Jcls.mname, Jcls.mname, Jcls.mname, Jcls.mname, jcls.mname)) Passdef Writecls2file (JCLs, F): F.seek (0, 2) # Write class header if is_parcelable: # If need implement parcelable if Jcls.mname = File_nam E:f.write (class_head_parcelable% ("", Jcls.mname, Jcls.mname, Jcls.mname)) Else:f.write (Cl Ass_head_parcelable% ("static", Jcls.mname, Jcls.mname, Jcls.mname)) Else:f.write (class_head% ("", Jcls.mname)) # write Class ' s a Ttribute for attribute in Jcls.mintegerlist:f.write (attribute_temp% (' int. ', attribute)) for attribute in JC Ls.mstrlist:f.write (attribute_temp% (' String ', Attribute)) for Attribute in Jcls.mbollist:f.write (Attr Ibute_temp% (' Boolean ', attribute)) for attribute in Jcls.mlistlist:f.write (attribute_temp% (' list< ' + att Ribute[0] + ' > ', Attribute[1]))) for attribute in Jcls.mclasslist:f.write (attribute_temp% (attribute[0], att RIBUTE[1]) # Write class ' s method Analyzerjson F.write (method_analyzer) for attribute in Jcls.mintegerli St:f.write (method_get_int% (attribute, attribute)) for attribute in Jcls.mstrlist:f.write (method_get_s Tring% (attribute, attribute)) for attribute in Jcls.mbollist:f.write (method_get_boolean% (attribute, Attribu TE)) for attribute in Jcls.mclasslist:f.write (method_get_class% (attribute[1], attribute[0], attribute[1], attribute[1]))) for Attri Bute in Jcls.mlistlist:f.write (method_get_list% (attribute[1], attribute[0], attribute[1], attribute[1], attribut        E[1], attribute[1], attribute[1], attribute[0], attribute[0], attribute[1], attribute[1])) F.write (Class_Method_END)     # Write Parcelable method if Is_parcelable:writeparcelabelmethod (f, JCLs) # the method toString F.write ("public string toString () {") F.write ("string allinfo =") for attribute in JCLS.MINTEGERLIST:F.W  Rite ("" "%s=" +%s + "% (attribute, attribute)) for attribute in Jcls.mstrlist:f.write ('" "%s=" +%s + " % (attribute, attribute))) for attribute in Jcls.mbollist:f.write ("" "%s=" +%s + "% (attribute, attribute)        ) for attribute in Jcls.mlistlist:f.write ("" "%s=" +%s.tostring () + ""% (Attribute[1], attribute[1])) For attribute in JCLs.Mclasslist:f.write ("%s=" +%s.tostring () + "% (Attribute[1], attribute[1])) f.write (" ' ""; "')    F.write ("return allinfo;") F.write (class_method_end) # Write class ' s class for Innerclass in Jcls.mInClassTypeList:writeCls2File (in  Nerclass, F) pass F.write (class_method_end) passdef generatorclsfile (JCLS): Global is_parcelable Global file_name is_parcelable = jcls.misparcelable file_name = jcls.mname f = open (file_name + ". Java", ' W ') F.writ  E (class_import% jcls.mpackagename) if Is_parcelable:f.write (class_import_parcelable) writecls2file (JCLs, F)

Full item: Http://files.cnblogs.com/files/chenjie0949/CodeGenerator1.3.zip

JSON turn JavaBean

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.