Use Json-lib to convert between Java and JSON "reprint"

Source: Internet
Author: User

1. Json-lib is a Java class library that provides the ability to convert Java objects, including beans, maps, collections, Java Arrays and XML, to JSON, or reverse-transform.

2. Json-lib Home: http://json-lib.sourceforge.net/

3. Execution Environment

The following class library support is required

    • Jakarta Commons-lang 2.5
    • Jakarta commons-beanutils 1.8.0
    • Jakarta commons-collections 3.2.1
    • Jakarta commons-logging 1.1.1
    • Ezmorph 1.0.6

4. Feature examples

The code example is given here through the junit-case example

 PackageCom.mai.json;Import Staticorg.junit.Assert.assertEquals;Importjava.util.ArrayList;Importjava.util.Date;ImportJava.util.HashMap;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Map;ImportNet.sf.ezmorph.Morpher;ImportNet.sf.ezmorph.MorpherRegistry;ImportNet.sf.ezmorph.bean.BeanMorpher;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;Importnet.sf.json.util.JSONUtils;Importorg.apache.commons.beanutils.PropertyUtils;Importorg.junit.Test; Public classJsonlibtest {/** Common Type, List, collection, etc. are resolved with Jsonarray * map, custom type is resolved with Jsonobject * Map can be understood as an object, the Key/value of the inside can be     To understand the property/property value of an object * that is {key1:value1,key2,value2 ...} * * 1.JSONObject is a name:values collection, obtained by its get (key) method is the corresponding value part of the key (string) * through its getjsonobject (key) can be taken to a JSON Object,--> converted to map, * Getjsonarray (key) can be taken to a jsonarray, * **/        //general arrays converted to JSON@Test Public voidTestarraytojson () {Boolean[] Boolarray =New Boolean[]{true,false,true}; Jsonarray Jsonarray=Jsonarray.fromobject (Boolarray);          System.out.println (Jsonarray); //prints [true,false,true]    }            //collection objects into JSON@Test Public voidTestlisttojson () {List List=NewArrayList (); List.add ("First" ); List.add ("Second" ); Jsonarray Jsonarray=jsonarray.fromobject (list);          System.out.println (Jsonarray); //prints ["First", "second"]    }            //the string JSON is converted to JSON, as the case may be with Jsonarray or Jsonobject@Test Public voidTestjsonstrtojson () {Jsonarray Jsonarray= Jsonarray.fromobject ("[' json ', ' is ', ' easy ']" );          System.out.println (Jsonarray); //prints ["JSON", "is", "easy"]    }            //The map is converted to JSON, using Jsonobject@Test Public voidTestmaptojson () {map map=NewHashMap (); Map.put ("Name", "JSON" ); Map.put ("BOOL", boolean.true); Map.put ("Int",NewInteger (1) ); Map.put ("Arr",NewString[]{"A", "B"} ); Map.put ("Func", "function (i) {return this.arr[i];}" ); Jsonobject Jsonobject=jsonobject.fromobject (map);      System.out.println (Jsonobject); }        //compound type bean turns into JSON@Test Public voidTestbeadtojson () {Mybean bean=NewMybean (); Bean.setid ("001"); Bean.setname ("Bank card"); Bean.setdate (NewDate ()); List Cardnum=NewArrayList (); Cardnum.add (Agricultural Bank); Cardnum.add (Icbc); Cardnum.add (Ccb); Cardnum.add (NewPerson ("test"));                Bean.setcardnum (Cardnum); Jsonobject Jsonobject=Jsonobject.fromobject (Bean);            System.out.println (Jsonobject); }        //normal types of JSON are converted into objects@Test Public voidTestjsontoobject ()throwsexception{String JSON= "{name=\" json\ ", Bool:true,int:1,double:2.2,func:function (a) {return A;},array:[1,2]}"; Jsonobject Jsonobject=Jsonobject.fromobject (JSON);        System.out.println (Jsonobject); Object Bean=Jsonobject.tobean (Jsonobject); Assertequals (Jsonobject.get ("Name"), Propertyutils.getproperty (Bean, "name") ) ); Assertequals (Jsonobject.get ("bool"), Propertyutils.getproperty (Bean, "bool") ) ); Assertequals (Jsonobject.get ("int"), Propertyutils.getproperty (Bean, "int") ) ); Assertequals (Jsonobject.get ("Double"), Propertyutils.getproperty (Bean, "double") ) ); Assertequals (Jsonobject.get ("Func"), Propertyutils.getproperty (Bean, "func") ) ); System.out.println (Propertyutils.getproperty (Bean,"Name")); System.out.println (Propertyutils.getproperty (Bean,"BOOL")); System.out.println (Propertyutils.getproperty (Bean,"Int")); System.out.println (Propertyutils.getproperty (Bean,"Double")); System.out.println (Propertyutils.getproperty (Bean,"Func")); System.out.println (Propertyutils.getproperty (Bean,"Array")); List arrayList= (List) jsonarray.tocollection (Jsonobject.getjsonarray ("array"));  for(Object object:arraylist) {System.out.println (object); }            }            //parses the JSON into a composite type object that contains the list@Test Public voidtestjsontobeanhavalist () {String json= "{list:[{name: ' test1 '},{name: ' test2 '}],map:{test1:{name: ' test1 '},test2:{name: ' Test2 '}}";//String json = "{list:[{name: ' test1 '},{name: ' Test2 '}]}";Map Classmap =NewHashMap (); Classmap.put ("List", person.class); Mybeanwithperson Diybean= (Mybeanwithperson) Jsonobject.tobean (Jsonobject.fromobject (JSON), Mybeanwithperson.class, Classmap);                System.out.println (Diybean); List List=diybean.getlist ();  for(Object o:list) {if(OinstanceofPerson ) {Person P=(person) o;            System.out.println (P.getname ()); }        }    }            //parses the JSON into a composite type object that contains the map@Test Public voidTestjsontobeanhavamap () {//think of map as an objectString json = "{list:[{name: ' test1 '},{name: ' test2 '}],map:{testone:{name: ' test1 '},testtwo:{name: ' Test2 '}}"; Map Classmap=NewHashMap (); Classmap.put ("List", person.class); Classmap.put ("Map", map.class); //use the hint to parse the JSON directly into the specified custom object, where list is fully parsed and map is not fully parsedMybeanwithperson Diybean = (Mybeanwithperson) Jsonobject.tobean (Jsonobject.fromobject (JSON), MyBeanWithPerson.class, Classmap);                System.out.println (Diybean); System.out.println ("Do the list release"); List<Person> list =diybean.getlist ();  for(person o:list) {person P=(person) o;        System.out.println (P.getname ()); } System.out.println ("Do the map release"); //To register the converter in the Registrar, you need to use the class in the Ezmorph packageMorpherregistry Morpherregistry =Jsonutils.getmorpherregistry (); Morpher Dynamorpher=NewBeanmorpher (person.class, Morpherregistry);                          Morpherregistry.registermorpher (Dynamorpher); Map Map=Diybean.getmap (); /*The map here does not have a type hint, so by default, the object stored as Net.sf.ezmorph.bean.MorphDynaBean type*/System.out.println (map); /*output: {testone=net.sf.ezmorph.bean.morphdynabean[email protected][{name=test1}], [email protect ed][{name=test2}]}*/List<Person> output =NewArrayList ();  for(Iterator i =map.values (). iterator (); I.hasnext ();) {              //using the Registrar to transform the specified Dynabean objectOutput.add (person) morpherregistry.morph.class, I.next ())); }                   for(person P:output) {System.out.println (P.getname ()); /*output: test1 test2*/        }            }}

Use Json-lib to convert between Java and JSON "reprint"

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.