The package used:
Commons-beanutils.jar
Commons-collections-3.1.jar
Commons-lang.jar
Commons-logging-1.1.3.jar
Ezmorph-1.0.jar
Json-lib-2.2.2-jdk15.jar
Let's look at the interaction between JSON and string.
User.java User Object
Package test; Public class User { String id; String name; int Age ; // Omit Get Set }
Json.java
Packagetest;ImportNet.sf.json.JSONObject; Public classjson{ Public Static voidMain (string[] args) {//String to JSONString Text = "{' id ': ' 001 ', ' name ': ' Jack ', ' age ': 22}"; Jsonobject Jo=jsonobject.fromobject (text); System.out.println (Jo.get ("id") + "__" + jo.get ("name") + "___" + jo.getint ("age")));
//a String-to-object equals the first turn to JSON and then to the objectString text2= "{' id ': ' 002 ', ' name ': ' Lion ', ' age ': 23}"; User U1= (user) Jsonobject.tobean (jsonobject.fromobject (text2), user.class); System.out.println (U1.getid ()+ "___" +u1.getname () + "__" +u1.getage ());
//Object Goto JSONUser U =NewUser (); U.setid ("003"); U.setage (25); U.setname ("Tom"); Jsonobject Jo2=jsonobject.fromobject (U); System.out.println (JO2); System.out.println (Jo2.get ("Name")); }}
Print output
001__jack___22
002___lion__23
{"Age": +, "id": "003", "name": "Tom"}
Tom
Add a new property to User.java book
Package test; Public class User { String id; String name; int Age ; Book book; // Get }
Book.java
Package test; Public class Book { String id; String name; // Get }
So what does it look like to turn the user into JSON?
Packagetest;ImportNet.sf.json.JSONObject; Public classJson { Public Static voidMain (string[] args) { book Book=NewBook (); Book. SetId ("111"); Book.setname (Language); User u=NewUser (); U.setid ("002"); U.setname ("Xim"); U.setbook (book); Jsonobject Jo=jsonobject.fromobject (U); System.out.println (Jo); }}
Output printing
{"Age": 0, "book": {"id": "111", "name": "Language"}, "id": "002", "name": "Xim"}
The method of mutual transfer is the same as the first one.
Java uses Json-lib objects, String,json