JSONObject basic content (1), JSONObject content (
Reference: http://swiftlet.net/archives/category/json. Thank you very much ~
It is not difficult to use a json object when you are working on a project. However, if you are not using it for a long time, you will forget it. So write down its basic usage.
Prerequisites: import related jar files:
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
Then you can develop it ~
1) convert javaBean to json
(1) Write A javaBean
public class User implements Serializable{ private static final long serialVersionUID = 1L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Then convert the javaBean to JSONObject:
Public static void main (String [] args) {// convert the an object to the json String User user = new User (); user. setUsername ("Rime"); user. setPassword ("1234"); JSONObject json1 = JSONObject. fromObject (user); System. out. println (json1.toString (); // map is converted to the json string HashMap <Object, Object> userMap = new HashMap <Object, Object> (); userMap. put ("username", "Rime"); userMap. put ("password", "1234"); JSONObject json2 = JSONObject. fromObject (userMap); System. out. println (json2.toString ());}
The output content is as follows:
{"Password": "1234", "username": "Rime "}
{"Username": "Rime", "password": "1234 "}
Here, you may wonder if any object can be converted to JSONObject? Of course, the answer is: no.
The JSONObject. fromObject (Object object) method is only valid for objects of the following type in the Set: 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 a "fake" Bean. Because it does not use the getXXX and setXXX methods to set and set values for the XXX attribute.
What if the object is a parameter of another type? For example, numbers, logical values, and strings in non-json format will produce empty JSONObject objects.