There are generally two ways to generate Jsonobject, either by JavaBean or by map type. As in the following example:
Define a user entity class first:
PackageCom.pcitc.json;/*** User entity class * * @Description *@authorAdmin * @created June 29, 2015 PM 3:43:15 *@version* @history *@see */ Public classUser { PublicString username; PublicString password; PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; }}
The test classes are as follows:
PackageCom.pcitc.json;ImportJava.util.HashMap;ImportNet.sf.json.JSONObject;/*** Test Class * * @Description *@authorAdmin * @created June 29, 2015 PM 3:57:01 *@version* @history *@see */ Public classTest { Public Static voidMain (String args[]) {User User=NewUser (); User.setusername ("Root"); User.setpassword ("1234"); //generating Jsonobject objects with JavaBeanJsonobject Json1 =jsonobject.fromobject (user); System.out.println ("JavaBean way: \ r \ n" +json1.tostring ()); HashMap<object, object> UserMap =NewHashmap<object, object>(); Usermap.put ("Username", "root"); Usermap.put ("Password", "1234"); //generate Jsonobject with the map typeJsonobject Json2 =Jsonobject.fromobject (UserMap); System.out.println ("Map mode: \ r \ n" +json2.tostring ()); }}
The test results are as follows:
Next, analyze the Jsonobject.fromobject () method from the source hierarchy:
Public Static jsonobject Fromobject (Object object) { returnnew jsonconfig ());}
The parameter types that this function can accept are: 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.
if (Jsonutils.isnumber (object) | | Jsonutils.isboolean (object) | | jsonutils.isstring (object)) { returnnew jsonobject ();}
There are two constructor functions for Jsonobject:
Public Jsonobject () { thisnew listorderedmap ();} Public Jsonobject (boolean isNull) { this(); this. nullobject = isNull;}
However, the first parameterless constructor is usually used, and the second constructor is rarely used.
JSON Learning Series (2)-How to generate Jsonobject