A brief introduction to the--json-lib of the Json Experience (iii)

Source: Internet
Author: User

This section is mainly about parsing JSON into Java.

Using Jsonserializer

1 // Using the Jsonserializer 2         Jsonarray Json2 = (jsonarray) Jsonserializer.tojson ("[[+]]"); 3         // convert JSON to list 4         List java2 = (list) Jsonserializer.tojava (json2); 5         System.out.println ("--convert JSON with Jsonserializer list--" + java2);     

Results

1 --convert JSON with Jsonserializer list--[1, 2, 3]

Converting JSON to java,string,number,boolean,list type can be resolved directly, other types will parse into Dynabean,java and JSON corresponding types are introduced in series one

1        //Json-lib can transform jsonobjects to either a dynabean or an specific bean class.2         //When using the Dynabean all arrays is converted to Lists3         //specific Bean Class The transformation would use type conversion if necessary on array properties.4 5         //Convert to Dynabean: Direct with Tobean method, String,number,boolean,list can be converted directly, other types are converted to Dynabean6String json = "{name=\" json\ ", Bool:true,int:1,double:2.2,func:function (a) {return A;},array:[1,2],map:{1:1,2:2}}";7Jsonobject Jsonobject =Jsonobject.fromobject (JSON);8Object Bean =Jsonobject.tobean (jsonobject);9 TenString name = (string) jsonobject.get ("name"); OneObject property = Propertyutils.getproperty (Bean, "name"); ASystem.out.println (Name.getclass () + "--" + Name + "|" -+ property.getclass () + "--" +Property ); -  theObject func = Jsonobject.get ("func"); -Object Funcproperty = Propertyutils.getproperty (Bean, "func"); -System.out.println (Func.getclass () + "--" + func + "|" -+ funcproperty.getclass () + "--" +funcproperty); +         //List expected = jsonarray.tolist (Jsonobject.getjsonarray ("array")); -Object array = jsonobject.get ("array"); +Object Arrayproperty = Propertyutils.getproperty (bean, "array"); ASystem.out.println (Array.getclass () + "--" + Array + "|" at+ arrayproperty.getclass () + "--" +arrayproperty); -Map map = (map) jsonobject.get ("map")); -Object Mapproperty = Propertyutils.getproperty (bean, "map"); -System.out.println (Map.getclass () + "--" + Map + "|" -+ mapproperty.getclass () + "--" + mapproperty);

Results

1 classjava.lang.string--json|classJava.lang.string--json2 classNet.sf.json.jsonfunction--function (a) {returnA }|classNet.sf.json.jsonfunction--function (a) {returnA;}3 classnet.sf.json.jsonarray--[1,2]|classJava.util.arraylist--[1, 2]4 classnet.sf.json.jsonobject--{"1": 1, "2": 2}|classNet.sf.ezmorph.bean.morphdynabean--[email protected][5{2=2, 1=1}

From the results, the map type directly uses the Tobean () method object is the Morphdynabean type, cannot directly parse out the concrete type, this kind of situation later has confessed how to do.

To parse a custom class, simply add the class object of the classes you want to convert in the Tobean () method

1         //Convert to Bean:json converting custom beans2String Json3 = "{id:\" 1\ ", Name:\" 123\ "}";3Jsonobject jsonObject3 =Jsonobject.fromobject (json3);4MyBean2 bean2 = (MyBean2) Jsonobject.tobean (JsonObject3, MyBean2.class);5Object objectName = jsonobject3.get ("name");6String name2 =bean2.getname ();7System.out.println (Objectname.getclass () + "--" + ObjectName + "|"8+ name2.getclass () + "--" + name2);

Results

1 class java.lang.string--123| class java.lang.string--123

In two special cases, the object contains a custom class that needs to be manually converted to the custom class

Official web-based explanation:

There is special cases when converting to an specific beans, if the target bean has a Map property and it must contain Other beans, would JSONObject.toBean() transform the nested beans into Dynabeans. If you need those nested beans transformed to an specific class, you can either postprocess the Map attribute or provide Hints on Jsonobject ' s attributes for conversion. May is JSONObject.toBean() passed a third argument, a Map, that would provide thos hints. Every key must is either the name of a property or a regular expression matching the object ' s properties, and the value MU St be a Class .

The second case was similar and it happens when the target Bean had a Collection (List) as a property and it must contain O ther beans. In this case the there is no-provide hints for class conversion. The only possible solution are to postprocess the collection transforming all Dynabean into a specific bean.

Two special cases, one is that the map contains a custom class, and the other is that the list contains custom classes, both of which need to be manually converted to the custom type, or you will get the Dynabean type.

We're building a Mybean3. This case, a list, a map contains a custom type of Mybean2, which is defined in series two and looks at the previous chapter.

1  Public classMYBEAN3 {2 3     PrivateList<mybean2> mybean2list =NewArraylist<mybean2>();4 5     Privatemap<string, mybean2> mybean2map =NewHashmap<string, mybean2>();6 7      PublicList<mybean2>getmybean2list () {8         returnmybean2list;9     }Ten      Public voidSetmybean2list (list<mybean2>mybean2list) { One          This. mybean2list =mybean2list; A     } -      PublicMap<string, mybean2>Getmybean2map () { -         returnMybean2map; the     } -      Public voidSetmybean2map (map<string, mybean2>Mybean2map) { -          This. Mybean2map =Mybean2map; -     } +  -}

The analytic approach to this situation

1String jsonMyBean3 = "{' mybean2list ': [{' id ': ' 1 ', ' name ': ' Mybean3 '}], ' Mybean2map ': {' 1 ': {' id ': ' 2 ', ' name ': ' Mybean3 '}} }";2Map CLASSMAP2 =NewHashMap ();3Classmap2.put ("Mybean2list", MyBean2.class);4         //classmap2.put ("Mybean2map", map.class);5MyBean3 mybean3 =(MYBEAN3) Jsonobject.tobean (6Jsonobject.fromobject (JSONMYBEAN3), MyBean3.class, CLASSMAP2);7System.out.println ("-------------"8+ mybean3.getmybean2list (). GetClass () + "|"9+ Mybean3.getmybean2map (). GetClass () + "|");Ten         //list<mybean2> mybean2list = Mybean3.getmybean2list (); OneMorpher Dynamorpher =NewBeanmorpher (MyBean2.class, A jsonutils.getmorpherregistry ()); -Morpherregistry Morpherregistry =Newmorpherregistry (); - Morpherregistry.registermorpher (dynamorpher); theList output =NewArrayList (); -          for(Iterator i =mybean3.getmybean2list (). iterator (); I.hasnext ();) { -Object morph = Morpherregistry.morph (MyBean2.class, I.next ()); - Output.add (morph); +         } - mybean3.setmybean2list (output); +         //Print Results A          for(MyBean2 object:mybean3.getMybean2List ()) { atSystem.out.println ("Special conversion list--" +object.getname ()); -         } -         //Map - Morpherregistry.registermorpher (dynamorpher); -Map Outputmap =NewHashMap (); -          for(Map.entry outMap:mybean3.getMybean2Map (). EntrySet ()) { inObject value =Outmap.getvalue (); - Outputmap.put (Outmap.getkey (), toMorpherregistry.morph (MyBean2.class, value)); +         } - Mybean3.setmybean2map (outputmap); the         //Output Partial results *          for(Map.entry<string, mybean2>Bean2Map:mybean3.getMybean2Map () $ . EntrySet ()) {Panax NotoginsengSystem.out.println ("Special conversion map--" + bean2map.getkey () + ":" -+Bean2map.getvalue ()); the         } +}

Results

1 Special conversion list--mybean3 December, 3:14:58 pm net.sf.ezmorph.bean.BeanMorpher morph2 Info: Property ' Com.r.json.jsonlib.mybean2.class ' has no write method. Skipped. 3 4 December 3:14:58 pm net.sf.ezmorph.bean.BeanMorpher morph5 Info: Property ' Com.r.json.jsonlib.mybean2.class ' has no write method. Skipped. 6 Special conversion Map--1:[email protected]

The list contains custom objects that can be placed in a map, with a classmap parameter in the Tobean () method, but it is not possible to test this parameter.

This package inconvenient place, this inside of the custom type need to manually convert, using the method in the example. In the result of printing some information, "no Write Method", after looking at the source code, is the Reflection class attribute, class object does not have the Write method, does not affect the parsing.

Summary: Parsing Java objects from JSON, general content using Jsonobject or Jsonarray Tobean method, if a custom type, using the Tobean method with class object parameters, if List,map contains a custom type, After you use the Tobean method, you manually convert the Dynabean type to the actual type.

A brief introduction to the--json-lib of the Json Experience (iii)

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.