1.JAR Package Introduction
To enable the program to run, the Json-lib package must be introduced, and the Json-lib package relies on the following jar packages:
- Commons-lang.jar
- Commons-beanutils.jar
- Commons-collections.jar
- Commons-logging.jar
- Ezmorph.jar
- Json-lib-2.2.2-jdk15.jar
2.JSONObject Object Use
The Json-lib package is a Beans,collections,maps,java arrays and XML and JSON transforms each other's packages. In this example, we will use the Jsonobject class to create the Jsonobject object, and then we print the values of those objects. In order to use the Jsonobject object, we will introduce the "Net.sf.json" package. To add elements to an object, we use the put () method.
1 Packagejsontest;2 3 ImportNet.sf.json.JSONArray;4 ImportNet.sf.json.JSONObject;5 6 Public classJsonobjectsample {7 8 //Create a Jsonobject object9 Private Staticjsonobject Createjsonobject () {TenJsonobject Jsonobject =NewJsonobject (); OneJsonobject.put ("username", "XXXX"); AJsonobject.put ("Sex", "male"); -Jsonobject.put ("QQ", "123456");
- returnJsonobject; - } - + Public Static voidMain (string[] args) { -Jsonobject jsonobject = Jsonobjectsample.createjsonobject ();//static method, directly through the class name + method call + //Output Jsonobject Object ASystem.out.println ("Jsonobject:" +jsonobject); at - //interpreting the type of the output object - BooleanIsArray =Jsonobject.isarray (); - BooleanIsEmpty =jsonobject.isempty (); - BooleanIsnullobject =Jsonobject.isnullobject (); -System.out.println ("is an array:" + IsArray + ", is empty:" +IsEmpty in+ ", Isnullobject:" +isnullobject); - to //adds an attribute, appending an element after jsonobject. +Jsonobject.element ("Address", "xx City xx Province"); -System.out.println ("Object after adding a property:" +jsonobject); the * //returns a Jsonarray object $Jsonarray Jsonarray =NewJsonarray ();Panax NotoginsengJsonarray.add (0, "This is a Jsonarray value"); -Jsonarray.add (1, "another Jsonarray value"); theJsonobject.element ("Jsonarray", Jsonarray); + //Add a jsonarray behind the Jsonobject . AJsonarray array = Jsonobject.getjsonarray ("Jsonarray"); the System.out.println (jsonobject); + - $System.out.println ("Returns a Jsonarray object:" +array); $ //value after adding Jsonarray -SYSTEM.OUT.PRINTLN ("result =" +jsonobject); the - //returns a string based on keyWuyiString username = jsonobject.getstring ("username"); theSystem.out.println ("username==>" +username); - Wu //convert characters to Jsonobject -String temp =jsonobject.tostring (); AboutJsonobject Object =Jsonobject.fromobject (temp); $ //return value after conversion based on key -System.out.println ("qq=" + object.get ("QQ"))); - - } A +}
Jsonobject and Jsonarray