Reference: Http://swiftlet.net/archives/category/json, thank you very much ~
Usually do the project, inevitably have encountered the use of JSON objects, this thing is not difficult, but one does not use for a long time, will forget, so the basic usage of it to write a bit.
Prerequisite: Import the relevant jar file:
Commons-lang-1.0.4.jar
Commons-collections-2.1.jar
Commons-beanutils-1.8.0.jar
Json-lib-2.4.jar
Ezmorph-1.0.6.jar
Commons-logging-1.1.jar
And then you can develop it.
A) JavaBean converted to JSON
(1) Write a JavaBean first
Public classUserImplementsserializable{Private Static Final LongSerialversionuid = 1L; PrivateString username; PrivateString password; PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; } }
Then convert this JavaBean to Jsonobject:
Public Static voidMain (string[] args) {//JavaBean object to JSON stringUser User =NewUser (); User.setusername ("Rime"); User.setpassword ("1234"); Jsonobject Json1=jsonobject.fromobject (user); System.out.println (Json1.tostring ()); //map conversion to JSON stringHashmap<object,object> UserMap =NewHashmap<object,object>(); Usermap.put ("username", "rime"); Usermap.put ("Password", "1234"); Jsonobject Json2=Jsonobject.fromobject (UserMap); System.out.println (Json2.tostring ()); }
The output reads as follows:
{"Password": "1234", "username": "Rime"}
{"username": "rime", "Password": "1234"}
See here, you may have doubts, is not what object can be converted to Jsonobject? The answer is of course: No.
The Jsonobject.fromobject (Object object) method is valid only for objects of the following set types: JSON formatted Strings,maps,dynabeans and JavaBeans.
"Note" Dynabeans is a dynamic bean defined by commons-beanutils. Dynabean is not a bean defined in Java, but rather a "fake" bean. Because it is not through the getxxx and Setxxx methods, the XXX property value and set the value.
What if object is another type of argument? For example, numbers, logical values, non-JSON-formatted strings, will produce empty Jsonobject objects.
Jsonobject Basic content (i)