How to Use JSONObject _ javascript skills

Source: Internet
Author: User
Tags package json string to json
The JSONObject-lib package is a package for conversion between beans, collections, maps, javaarrays, and xml and JSON. This article describes how to use jsonobject. 1. Introduction to JSONObject

The JSONObject-lib package is a package that converts beans, collections, maps, java arrays, xml, and JSON.

2. Download the jar package

Http://files.cnblogs.com/java-pan/lib.rar

Provides six jar packages other than JSONObject's jar packages, a total of seven jar files

Note: because the project version used in the work is 1.1 corresponding to JDK 1.1, this blog is based on version.

Corresponding to this version of javadoc download path: http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-1.1/

The latest version is 2.4, and other versions are http://sourceforge.net/projects/json-lib/files/json-lib/

3. Project Environment:

System: WIN7 myeclipse: 6.5 tomcat: 5.0 JDK: the development environment and compilation are both 1.5

The project structure is as follows:

Note: Only the jsonobject_1_3class and note.txt class under the jsonpackage of the project can be used in this document.

4. class & method Based on 1.1 APIs

Make the following conventions:

1. Describes JSONObject 1.1-based APIs.

2. Only common classes and methods are introduced.

3. We will not describe this version any more.

4. The classes and methods introduced mainly focus on

JSONObject:A JSONObject is an unordered collection of name/value pairs.

Is a final class that inherits the Object and implements the JSON interface.

The constructor is as follows:

JSONObject (); creates an empty JSONObject

JSONObject (boolean isNull); creates a JSONObject that is empty or not.

The common method is as follows:

FromBean (Object bean); static method. Create a JSONObject Object through a pojo Object

FromJSONObject (JSONObject object); static method, constructs a JSONObject object through another JSONObject object

FromJSONString (JSONString string); static method. A JSONString is used to create a JSONObject object.

ToString (); converts a JSONObject object to a json string.

Iterator (); returns an Iterator object to traverse elements.

The following are some put/get methods, which need to be emphasized by the Common get method and pot method. This is described in the API as follows:

A get method returns a value if one can be found, and throws an exception if one cannot be found. an opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

JSONArray: A JSONArray is an ordered sequence of values.

Is a final class that inherits the Object and implements the JSON interface.

The constructor is as follows:

JSONArray (); construct an empty JSONArray object

The common method is as follows:

FromArray (Object [] array); static method, creates a JSONArray Object through a java array

FromCollection (Collection collection); static method, creates a JSONArray object through the collection object

FromString (String string); static method. A JSONArray object is constructed using a json String.

ToString (); converts a JSONArray object to a string in json format

Iterator (); returns an Iterator object to traverse elements.

The following is the put/get method ......

XMLSerializer: Utility class for transforming JSON to XML an back.

A class inherited from the Object

The constructor is as follows:

XMLSerializer (); Create an XMLSerializer object

The common method is as follows:

SetRootName (String rootName); set the name of the root element of the converted xml

SetTypeHintsEnabled (boolean typeHintsEnabled); Sets whether the type attribute is displayed for each element.

Write (JSON json); converts a json object to xml, the default character encoding is UTF-8,

You can use write (JSON json, String encoding) for encoding)

5. A simple example of XML and JSON string Columns

JSON:

{"Password": "123456", "username": "Zhang San "}

Xml

<? Xml version = "1.0" encoding = "UTF-8"?>
 
  
   
123456
  
  
   
Zhang San
  
 

Start

Create a web project named "JS" and import the following seven jar packages. The file is downloaded from the previous preparation.

Note: you do not need to create a web project. You can also perform this operation for common java projects. For example, if you want to import another 6 packages to the jsonpackage, I Will paste the note.txt at the end.

Question1: What should I do if the backend receives strings in json format at the front end?

Public static void jsonToJAVA () {System. out. println ("json String to java code"); String jsonStr = "{\" password \ ": \" \ ", \" username \": \ "Zhang San \"} "; JSONObject jsonObj = JSONObject. fromString (jsonStr); String username = jsonObj. getString ("username"); String password = jsonObj. optString ("password"); System. out. println ("json ---> java \ n username =" + username + "\ t password =" + password );}

Question2: How does one assemble strings in json format in the background?

Public static void javaToJSON () {System. out. println ("java code encapsulated as a json string"); JSONObject jsonObj = new JSONObject (); jsonObj. put ("username", "zhangsan"); jsonObj. put ("password", ""); System. out. println ("java ---> json \ n" + jsonObj. toString ());}

Question3: how to convert a json string to an xml string?

Public static void jsonToXML () {System. out. println ("json String to xml String"); String jsonStr = "{\" password \ ": \" \ ", \" username \": \ "Zhang San \"} "; JSONObject json = JSONObject. fromString (jsonStr); XMLSerializer xmlSerializer = new XMLSerializer (); xmlSerializer. setRootName ("user_info"); xmlSerializer. setTypeHintsEnabled (false); String xml = xmlSerializer. write (json); System. out. println ("json ---> xml \ n" + xml );}

Question4: how to convert a string in xml format to a string in json format?

Public static void xmlToJSON () {System. out. println ("Convert xml String to json String"); String xml = "<? Xml version = \ ". \" encoding = \ "UTF-\"?>
 
  
  
   
Zhang San
  
 "; JSON json = XMLSerializer. read (xml); System. out. println (" xml ---> json \ n "+ json. toString ());}

Question5: how to convert a javabean to a json string?

Public static void javaBeanToJSON () {System. out. println (" an to json string"); UserInfo userInfo = new UserInfo (); userInfo. setUsername ("Zhang San"); userInfo. setPassword (""); JSONObject json = JSONObject. fromBean (userInfo); System. out. println ("javabean ---> json \ n" + json. toString ());}

Question6: how to convert a javabean to an xml string?

Public static void javaBeanToXML () {System. out. println ("javabean to xml string"); UserInfo userInfo = new UserInfo (); userInfo. setUsername ("Zhang San"); userInfo. setPassword (""); JSONObject json = JSONObject. fromBean (userInfo); XMLSerializer xmlSerializer = new XMLSerializer (); String xml = xmlSerializer. write (json, "UTF-"); System. out. println ("javabean ---> xml \ n" + xml );}

The complete jsonobject_00003.java code is as follows:

JSONObject_1_3 package json; import net. sf. json. JSON; import net. sf. json. JSONObject; import net. sf. json. xml. XMLSerializer; public class JSONObject _ {public static void javaToJSON () {System. out. println ("java code encapsulated as a json string"); JSONObject jsonObj = new JSONObject (); jsonObj. put ("username", "zhangsan"); jsonObj. put ("password", ""); System. out. println ("java ---> json \ n" + jsonObj. toString ();} public static v Oid jsonToJAVA () {System. out. println ("json String to java code"); String jsonStr = "{\" password \ ": \" \ ", \" username \": \ "Zhang San \"} "; JSONObject jsonObj = JSONObject. fromString (jsonStr); String username = jsonObj. getString ("username"); String password = jsonObj. optString ("password"); System. out. println ("json ---> java \ n username =" + username + "\ t password =" + password);} public static void jsonToXML () {System. out. Println ("json String to xml String"); String jsonStr = "{\" password \ ": \" \ ", \" username \": \ "Zhang San \"} "; JSONObject json = JSONObject. fromString (jsonStr); XMLSerializer xmlSerializer = new XMLSerializer (); xmlSerializer. setRootName ("user_info"); xmlSerializer. setTypeHintsEnabled (false); String xml = xmlSerializer. write (json); System. out. println ("json ---> xml \ n" + xml);} public static void javaBeanToJSON () {e M. out. println (" an to json string"); UserInfo userInfo = new UserInfo (); userInfo. setUsername ("Zhang San"); userInfo. setPassword (""); JSONObject json = JSONObject. fromBean (userInfo); System. out. println ("javabean ---> json \ n" + json. toString ();} public static void javaBeanToXML () {System. out. println ("javabean to xml string"); UserInfo userInfo = new UserInfo (); userInfo. setUsername ("Zhang San"); userInfo. setPassword ("" ); JSONObject json = JSONObject. fromBean (userInfo); XMLSerializer xmlSerializer = new XMLSerializer (); String xml = xmlSerializer. write (json, "UTF-"); System. out. println ("javabean ---> xml \ n" + xml);} public static void xmlToJSON () {System. out. println ("Convert xml String to json String"); String xml = "<? Xml version = \ ". \" encoding = \ "UTF-\"?>
 
  
  
   
Zhang San
  
 "; JSON json = XMLSerializer. read (xml); System. out. println ("xml ---> json \ n" + json. toString ();} public static void main (String args []) {// javaToJSON (); // jsonToJAVA (); // jsonToXML (); // javaBeanToJSON (); // javaBeanToXML (); xmlToJSON ();}}

The complete UserInfo. java code is as follows:

UserInfo package json; public class UserInfo { public String username; public 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; } }

Result

Both the code and running results are attached to the back of each problem. When running, you can directly run the main method on each method to see the test results.

Note.txt is the corresponding error and solution. It also explains why to import the jar package mentioned above;

The content of the note.txt file is as follows:

java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(URLClassLoader.java:55) at java.net.URLClassLoader$1.run(URLClassLoader.java:194) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302) at generate.TestJSONObject.main(TestJSONObject.java:40) Exception in thread "main" 

Solution: Import commons-lang-2.1.jar

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at net.sf.json.JSONObject.
 
  (JSONObject.java:125) at generate.TestJSONObject.main(TestJSONObject.java:40) Exception in thread "main" 
 

Solution: Import commons-logging.jar

java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean at net.sf.json.JSONObject.set(JSONObject.java:2164) at net.sf.json.JSONObject.put(JSONObject.java:1853) at net.sf.json.JSONObject.put(JSONObject.java:1806) at generate.TestJSONObject.main(TestJSONObject.java:41) Exception in thread "main" 

Solution: Import commons-beanutils.jar

java.lang.NoClassDefFoundError: net/sf/ezmorph/MorpherRegistry at net.sf.json.util.JSONUtils.
 
  (JSONUtils.java:65) at net.sf.json.JSONObject.set(JSONObject.java:2164) at net.sf.json.JSONObject.put(JSONObject.java:1853) at net.sf.json.JSONObject.put(JSONObject.java:1806) at generate.TestJSONObject.main(TestJSONObject.java:41) Exception in thread "main" 
 

Solution: Import ezmorph-1.0.2.jar

java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap at org.apache.commons.beanutils.PropertyUtils.
 
  (PropertyUtils.java:208) at net.sf.json.JSONObject.fromBean(JSONObject.java:190) at net.sf.json.JSONObject.fromObject(JSONObject.java:437) at net.sf.json.JSONObject.set(JSONObject.java:2196) at net.sf.json.JSONObject.put(JSONObject.java:1853) at net.sf.json.JSONObject.put(JSONObject.java:1806) at generate.TestJSONObject.main(TestJSONObject.java:41) Exception in thread "main" 
 

Solution: Import commons-collections-3.0.jar

Exception in thread "main" java.lang.NoClassDefFoundError: nu/xom/Serializer at generate.TestJSONObject.jsonToXML(TestJSONObject.java:88) at generate.TestJSONObject.main(TestJSONObject.java:96) 

Solution: Import xom-1.0d10.jar

Notes:

1. Pay attention to the modifier of the UserInfo class, and use the public modifier. the username and password variables are also modified with the public modifier. It is best to write a class separately, so it will not be pasted here.

2. The preceding json string and xml string are the simplest forms. In actual development, the json string and xml format are much more complex than this one,

To process complex json strings, you can encapsulate and write A class to inherit HashMap, and then rewrite its put and get methods to support A [0] type. B and. reading and specifying the key value of B

3. In the above 6 cases, some of them may not exist or are not commonly used in actual development.

Problems:

1. Chinese garbled characters generated using the write method of XMLSerializer

2. Red log problems in question4

The above content is a detailed explanation of how to use JSONObject. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.