Reference: Http://swiftlet.net/archives/category/json Thank you very much!!! ~~
The third article, mainly about two points: 1. How to obtain the value of the corresponding key in Jsonobject. 2. How to convert Jsonobject to JavaBean object.
A) Get the property value in Jsonobject
First we write a JavaBean class
Public classEMP {PrivateString name; PrivateInteger age; Private Booleanmarried; Public Booleanismarried () {returnmarried; } Public voidSetmarried (Booleanmarried) { This. married =married; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicInteger getage () {returnAge ; } Public voidsetage (Integer age) { This. Age =Age ; }}
Then, according to the normal method, generate the object, convert it to Jsonobject, and then look at the comment bar ~
Public Static voidMain (string[] args) {emp emp=NewEmp (); Emp.setname ("Rime"); Emp.setage (23); Emp.setmarried (false); //Convert to JsonobjectJsonobject JSON =jsonobject.fromobject (EMP); System.out.println (Json.tostring ()); //use key to get property value, similar to mapString name = json.getstring ("name"); Integer Age= Json.getint ("Age"); Booleanmarried = Json.getboolean ("Married"); SYSTEM.OUT.PRINTLN (Name+ "," + Age + "," +married); }
Output Result:
{"Age": $, "married": false, "name": "Rime"}
Rime,23,false
See here you may have doubts, (1) If Jsonobject does not exist in this key, what will happen? (2) The type of the value corresponding to this key is wrong, what should I do? (3) What if value is a complex data type?
Since there is doubt, then we have one solution.
(1) We deliberately put "name" wrong, written as "Nane", the result system error:
Exception in thread "main" net.sf.json.jsonexception:jsonobject["Nane") not found
To prevent this anomaly, we can use the Optxxx method instead of the GetXXX method.
That
String name = json.optstring ("Nane"); // When the key does not exist in Jsonobject, you can use OPTXXX to get null or default values instead of reporting exceptions
Set Default values:
String name = json.optstring ("Nane", "notexits");
After setting the default, the Notexits string is returned when the Nane property does not exist.
(2) We modify the program
String name = json.getstring ("Age"); Boolean married = Json.getboolean ("name"); = Json.getint ("name");
Run the program, will error:
Exception in thread "main" net.sf.json.jsonexception:jsonobject["name"] is not a Boolean.
Exception in thread "main" net.sf.json.jsonexception:jsonobject["name"] was not a number. This type of error.
It is important to note that {"Age": "Married": false, "name": "false"}, where false with "" is a Boolean type, quoted is a string type.
Also, most types can be converted to string types, but not in the opposite way.
(3) Complex data types
Write a bean with a complex point
Public classStudentImplementsserializable{Private Static Final LongSerialversionuid = 1L; PrivateString sname; PrivateInteger age; PrivateDate Birth; PrivateList<string>courses; PrivateMap<string,string>photo; PrivateEMP EMP;
Then, build the object, assign a value to the property
Public Static voidMain (string[] args) {Student s=NewStudent (); List<String> sList =NewLinkedlist<string>(); Map<String,String> photos =NewHashmap<string,string>(); EMP EMP=NewEmp (); Emp.setname ("Me"); Emp.setage (10); Emp.setmarried (false); Slist.add (A); Slist.add ("B"); Photos.put ("C", "C"); Photos.put ("D", "D"); S.setsname ("EZ"); S.setage (23); S.setbirth (NewDate ()); S.setcourses (sList); S.setphoto (Photos); S.setemp (EMP); Jsonobject Jsonobject=Jsonobject.fromobject (s); System.out.println (Jsonobject.tostring ()); //jsonobject conversion to JavaBeanStudent Student = (Student) Jsonobject.tobean (Jsonobject, Student.class); System.out.println (Student.getsname ()+ ";" + student.getage () + ";" +student.getbirth () + ";" + student.getcourses (). Get (1) + ";" + Student.getphoto (). Get ("C") + ";" +student.getemp ()); }
Operation Result:
{"Age": $, "birth": {"date": 7, "Day": 2, "hours": +, "minutes": +, "month": 6, "Seconds": "Time": 1436261073641, " Timezoneoffset ": -480," Year ":" A "," Courses ": [" a "," B "]," emp ": {" Age ": Ten," Married ": false," name ":" Me "}," Photo ": {" D " : "D", "C": "C"}, "Sname": "EZ"}
2015-7-7 17:24:33 Net.sf.json.JSONObject Tobean
Info: Property ' Day ' of class java.util.Date has no write method. Skipped.
2015-7-7 17:24:33 Net.sf.json.JSONObject Tobean
Information: Property ' Timezoneoffset ' of class java.util.Date have no write method. Skipped.
ez;23; Tue Jul 17:24:33 CST 2015;b;c; [Email protected]
Although the data has been successfully converted back, but there is a warning message, it is always impossible to ease down.
If you look closely, you can see that the above warning is a warning about java.util.Date, so what is the Date type to do with it?
Also, pay attention to "birth": {"date": 8, "Day": 3, "hours": one, "minutes": One, "month": 6, "Seconds": "Time": 1436325091564, " Timezoneoffset ": -480," Year ": 115},
You will find the data in this format very difficult to understand, and we generally use the YYYY-MM-DD format.
II) Date Type
For the conversion of the date type, we can do it through the converter.
Write a translator first:
Public classJsondatevalueprocessorImplementsJsonvalueprocessor {PrivateString Datepattern = "Yyyy-mm-dd"; Publicjsondatevalueprocessor () {Super(); } Publicjsondatevalueprocessor (String format) {Super(); This. Datepattern =format; } @Override PublicObject Processarrayvalue (object value, Jsonconfig jsonconfig) {returnprocess (value); } @Override PublicObject Processobjectvalue (String key, object value, Jsonconfig jsonconfig) {returnprocess (value); } PrivateObject Process (object value) {Try { if(ValueinstanceofDate) {SimpleDateFormat SDF=NewSimpleDateFormat (Datepattern, locale.uk); returnSdf.format ((Date) value); } returnValue = =NULL? "": Value.tostring (); } Catch(Exception e) {return""; } } PublicString Getdatepattern () {returnDatepattern; } Public voidSetdatepattern (String pdatepattern) {Datepattern=Pdatepattern; }}
Then test it again:
Public Static void Main (string[] args) { new Student (); S.setbirth (new Date ()); New jsonconfig (); Config.registerjsonvalueprocessor (Date. class New jsondatevalueprocessor ()); = Jsonobject.fromobject (s,config); System.out.println (Jsonobject.tostring ()); }
The result of the final output
{"Age": 0, "Birth": "2015-07-08", "courses": [], "EMP": null, "photo": null, "sname": ""}
Jsonobject Basic Content (iii)