Jsonobject use method to explain _javascript skills

Source: Internet
Author: User
Tags package json string to json

1.JSONObject Introduction

The Jsonobject-lib package is a Beans,collections,maps,java arrays and XML and JSON-converted packages.

2. Download Jar Pack

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

Provides 6 additional jar packages that are dependent on outside of the Jsonobject jar, with a total of 7 jar files

Description: Because the project used in the work of the version is 1.1 of the corresponding jdk1.3 version, so this blog is based on the 1.1 version of the introduction.

The Javadoc download path corresponding to this version is as follows: HTTP://SOURCEFORGE.NET/PROJECTS/JSON-LIB/FILES/JSON-LIB/JSON-LIB-1.1/

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

3. Project Environment:

system:win7 myeclipse:6.5 tomcat:5.0 JDK: Development environment and compilation with 1.5

The project structure is as follows:

Description: The file used only in the Engineering directory JSON package Jsonobject_1_3 class and Note.txt

4.class&method 1.1-based API

Make the following conventions:

1. Introducing the API based on Jsonobject 1.1

2. Describe only the common classes and methods

3. No longer recommend the use of this version is no longer recommended

4. The classes and methods introduced are mainly used in this blog

Jsonobject:a Jsonobject is a unordered collection of name/value pairs.

is a final class that inherits the object and implements the JSON interface

The construction method is as follows:

Jsonobject (); Create an empty Jsonobject object

Jsonobject (Boolean isNull); Create a Jsonobject object that is empty

The common method is as follows:

Frombean (object bean); A static method that creates a Jsonobject object through a Pojo object

Fromjsonobject (Jsonobject object); A static method that constructs a Jsonobject object from another Jsonobject object

Fromjsonstring (jsonstring string); static method, creating a Jsonobject object from a jsonstring

ToString (); Converts a Jsonobject object to a JSON-formatted string

Iterator (); Returns a iterator object to traverse the element

Then there are some put/get methods that require common get methods and pot methods to do the emphasis, as described in the API:

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

Jsonarray:a Jsonarray is a ordered sequence of values.

is a final class that inherits the object and implements the JSON interface

The construction method is as follows:

Jsonarray (); Construct an empty Jsonarray object

The common method is as follows:

FromArray (object[] array); static method, creating a Jsonarray object from a Java array

Fromcollection (Collection Collection); static method, creating a Jsonarray object by Collection the collection object

FromString (string string); A static method that constructs a Jsonarray object through a JSON-formatted string

ToString (); Converts a Jsonarray object to a JSON-formatted string

Iterator (); Returns a iterator object to traverse the element

The following is also the Put/get method ...

Xmlserializer:utility class for transforming JSON to XML a back.

A class that inherits from Object

The construction method is as follows:

XMLSerializer (); Create a XMLSerializer object

The common method is as follows:

Setrootname (String rootname); Set the root element name of the converted XML

Settypehintsenabled (Boolean typehintsenabled); set whether each element displays the Type property

Write (JSON JSON); Convert the JSON object to XML, the default character encoding is UTF-8,

You need to set the encoding to use write (JSON JSON, String encoding)

5. A simple example of XML and JSON string columns

Json:

{"Password": "123456", "username": "John"}

Xml

<?xml version= "1.0" encoding= "UTF-8"?> 
<user_info>
<password>123456</password>
<username> John </username>
</user_info>

Start

New Web project, project name JS, import the following 7 jar packages, files in the previous preparation to download the path.

Description: You can not create a new Web project, ordinary Java engineering can also complete the operation of this article. As for why to import 6 other packages outside of the JSON package, I'll put the note.txt in the end, and you'll know when you see it.

Question1: What do I do with the JSON-formatted string in the background?

 public static void Jsontojava () {
 System.out.println ("JSON string to Java code");
 String jsonstr = "{\ password\": \ "\", \ "username\": \ "john \"};
 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 the backend assemble a JSON-formatted string?

 public static void Javatojson () {
 System.out.println ("Java code encapsulated as JSON string");
 Jsonobject jsonobj = new Jsonobject ();
 Jsonobj.put ("username", "John");
 Jsonobj.put ("Password", "");
 SYSTEM.OUT.PRINTLN ("Java--->json \ n" + jsonobj.tostring ());
 }

How do strings in Question3:json format be converted to XML-formatted strings?

 public static void Jsontoxml () {
 System.out.println ("JSON string to XML string");
 String jsonstr = "{\ password\": \ "\", \ "username\": \ "john \"};
 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);
 }

How does a string in the Question4:xml format convert to a JSON-formatted string?

public static void Xmltojson () {
 System.out.println ("XML string to JSON string");
 String xml = "<?xml version=\". \ "encoding=\" utf-\ "?><user_info><password></password>< Username> John </username></user_info> ";
 JSON json=xmlserializer.read (XML);
 SYSTEM.OUT.PRINTLN ("XML--->json \ n" +json.tostring ());
 }

How does Question5:javabean convert to a JSON string?

public static void Javabeantojson () {
 System.out.println ("JavaBean to JSON string");
 UserInfo UserInfo = new UserInfo ();
 Userinfo.setusername ("John");
 Userinfo.setpassword ("");
 Jsonobject json = Jsonobject.frombean (userInfo);
 System.out.println ("JavaBean--->json \ n" + json.tostring ());
 }

How do question6:javabean convert to XML strings?

public static void Javabeantoxml () {
 System.out.println ("JavaBean to XML string");
 UserInfo UserInfo = new UserInfo ();
 Userinfo.setusername ("John");
 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_1_3.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 JSON string");
 Jsonobject jsonobj = new Jsonobject ();
 Jsonobj.put ("username", "John");
 Jsonobj.put ("Password", "");
 SYSTEM.OUT.PRINTLN ("Java--->json \ n" + jsonobj.tostring ());
 public static void Jsontojava () {System.out.println ("JSON string to Java code");
 String jsonstr = "{\ password\": \ "\", \ "username\": \ "john \"};
 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\": \ "john \"};
 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 () {System.out.println ("JavaBean to JSON string");
 UserInfo UserInfo = new UserInfo ();
 Userinfo.setusername ("John");
 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 ("John");
 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 ("XML string to JSON string"); String xml = "<?xml version=\". \ encoding=\ "utf-\"? >&Lt;user_info><password></password><username> John </username></user_info> ";
 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 the results of the operation have been posted behind each problem, and the runtime can see the test results directly with the main method running on each method separately.

Note.txt is the corresponding error and solution to the report, and another aspect explains why you need to import the jar package mentioned earlier;

The contents of the Note.txt file are 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.<clinit > (jsonobject.java:125) at 
generate. Testjsonobject.main (TESTJSONOBJECT.JAVA:40) 

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) 

Solution: Import Commons-beanutils.jar

Java.lang.noclassdeffounderror:net/sf/ezmorph/morpherregistry at 
net.sf.json.util.jsonutils.<clinit> ( jsonutils.java:65) at 
Net.sf.json.JSONObject.set (jsonobject.java:2164) at 
Net.sf.json.JSONObject.put ( jsonobject.java:1853) at the 
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.<clinit> (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) 

Solution: Import Commons-collections-3.0.jar

Exception in thread ' main ' java.lang.noclassdeffounderror:nu/xom/serializer at 
generate. Testjsonobject.jsontoxml (testjsonobject.java:88) 

Solution: Import Xom-1.0d10.jar

A few notes:

1. Note that the modifiers of the UserInfo class, with public modification, variable username and password are also decorated with public, it is best to write a separate class, here is not posted

2. The above JSON string and XML string are the simplest forms, and the actual development of the JSON string and XML format is much more complex than this,

Handles complex JSON strings, encapsulates writing a class to inherit HashMap, and then overrides its put and get methods to support the type a[0]. Reading and specifying key values for B and a.b

3. The above 6 situations may not exist or are not commonly used in actual development

The problems that exist:

1. The Chinese garbled problem of XML strings generated using the XmlSerializer write method

The red log logs in the 2.question4 problem

The above content is small make up to everybody introduces Jsonobject use method detailed, hope everybody likes.

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.