For more information about JSON, see the json Getting Started Guide.

Source: Internet
Author: User
Tags unsupported

Although there are many ideas about how XML has the cross-platform and cross-language advantages, unless it is applied to Web Services, in common Web applications, developers often use their brains for XML parsing. Whether the server generates or processes XML, or the client uses JavaScript to parse XML, it often leads to complicated code and extremely low development efficiency. In fact, for most Web applications, they do not need complicated XML to transmit data at all, and XML scalability is rarely advantageous. Many AJAX applications even directly return HTML fragments to build dynamic Web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but at the same time lacks some flexibility.
JSON provides another data exchange format for Web application developers. Let's take a look at what JSON is. JSON provides better simplicity and flexibility than XML or HTML fragments.
Ajax Resource Center
Visit the Ajax Resource Center, an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.
JSON Data Format Parsing
Like XML, JSON is also based on plain text data format. Because JSON is designed for JavaScript, The JSON data format is very simple. You can use JSON to transmit a simple String, Number, or Boolean, or an array, or a complex Object.
String, Number, and Boolean are very simple in JSON format. For example, JSON represents a simple String "abc" in the format:
"Abc"
In addition to the characters ", \,/and some control operators (\ B, \ f, \ n, \ r, \ t), other Unicode characters can be directly output. Is a complete String representation structure:
Figure 1. Complete String representation structure
A Number can be expressed as follows based on an integer or floating point:
Figure 2. Number representation structure
This is consistent with the representation of the vast majority of programming languages, such:
12345 (integer)
-3.9e10 (floating point number)
Boolean Type: true or false. In addition, null in JavaScript is expressed as null. Note that neither true, false, nor null has double quotation marks. Otherwise, it is considered as a String.
JSON can also represent an array object. [] is used to contain all elements. Each element is separated by commas. The element can be any Value. For example, the following array contains a String, Number, boolean and null:
["Abc", 12345, false, null]
The Object is represented by a series of unordered Key-Value pairs in JSON. In fact, the Object here is equivalent to the Map <String, Object> in Java, instead of Java Class. Note that the Key can only be represented by String.
For example, an Address object contains the following Key-Value:
City: Beijing
Street: Chaoyang Road
Postcode: 100025 (integer)
JSON format:
{& Quot; city & quot;: & quot; Beijing & quot;, & quot; street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}
Value can also be another Object or array. Therefore, a complex Object can be nested. For example, a Person Object contains the name and address objects, which can be expressed as follows:
{"Name": "Michael", "address ":
{& Quot; city & quot;: & quot; Beijing & quot;, & quot; street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}
}
JavaScript processing JSON data
This section describes how to use JSON to represent data. Next, we also need to solve how to generate JSON-format data on the server to send data to the client, and how to use JavaScript to process JSON-format data on the client.
We will first discuss how to process JSON data in JavaScript on a Web page. Using a simple JavaScript method, we can see how the client expresses JSON data to users:
Function handleJson (){
Var j = {"name": "Michael", "address ":
{& Quot; city & quot;: & quot; Beijing & quot;, & quot; street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}
};
Document. write (j. name );
Document. write (j. address. city );
}
Assume that the JSON data returned by the server is as follows:
{"Name": "Michael", "address ":
{& Quot; city & quot;: & quot; Beijing & quot;, & quot; street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}
}
You only need to assign a value to a JavaScript variable to use the variable immediately and update the information on the page. JSON is easy to use than XML to read various nodes from the DOM. All we need to do is send an Ajax request and assign the JSON data returned by the server to a variable. Many Ajax frameworks already include the ability to process JSON data, such as Prototype (a popular JavaScript Library: http://prototypejs.org) that provides the evalJSON () method, directly convert the JSON text returned by the server into a JavaScript variable:
New Ajax. Request ("http: // url ",{
Method: "get ",
OnSuccess: function (transport ){
Var json = transport. responseText. evalJSON ();
// TODO: document. write (json. xxx );
}
});
Server output JSON format data
Next we will discuss how to output data in JSON format on the server side. Taking Java as an example, we will demonstrate how to encode a Java object as a JSON text.
When you encode a String object in JSON format, you only need to process special characters. In addition, the string must be (") rather: Copy codeThe Code is as follows: static String string2Json (String s ){
StringBuilder sb = new StringBuilder (s. length () + 20 );
Sb. append ('\"');
For (int I = 0; I <s. length (); I ++ ){
Char c = s. charAt (I );
Switch (c ){
Case '\"':
Sb. append ("\\\"");
Break;
Case '\\':
Sb. append ("\\\\");
Break;
Case '/':
Sb. append ("\\/");
Break;
Case '\ B ':
Sb. append ("\ B ");
Break;
Case '\ F ':
Sb. append ("\ f ");
Break;
Case '\ N ':
Sb. append ("\ n ");
Break;
Case '\ R ':
Sb. append ("\ r ");
Break;
Case '\ t ':
Sb. append ("\ t ");
Break;
Default:
Sb. append (c );
}
}
Sb. append ('\"');
Return sb. toString ();
}

It is much easier to express Number as JSON. Using Java polymorphism, we can handle multiple Number formats such as Integer, Long, and Float:Copy codeThe Code is as follows: static String number2Json (Number number Number ){
Return number. toString ();
}

The Boolean type can also be directly represented in JSON using the toString () method:Copy codeThe Code is as follows: static String boolean2Json (Boolean bool ){
Return bool. toString ();
}

To encode an array in JSON format, you can encode each element in a loop:Copy codeThe Code is as follows: static String array2Json (Object [] array ){
If (array. length = 0)
Return "[]";
StringBuilder sb = new StringBuilder (array. length <4 );
Sb. append ('[');
For (Object o: array ){
Sb. append (toJson (o ));
Sb. append (',');
}
// Change the last ',' to ']':
Sb. setCharAt (sb. length ()-1, ']');
Return sb. toString ();
}

Finally, we need to encode Map <String, Object> In JSON format, because the JavaScript Object actually corresponds to the Java Map <String, Object>. The method is as follows:Copy codeThe Code is as follows: static String map2Json (Map <String, Object> map ){
If (map. isEmpty ())
Return "{}";
StringBuilder sb = new StringBuilder (map. size () <4 );
Sb. append ('{');
Set <String> keys = map. keySet ();
For (String key: keys ){
Object value = map. get (key );
Sb. append ('\"');
Sb. append (key );
Sb. append ('\"');
Sb. append (':');
Sb. append (toJson (value ));
Sb. append (',');
}
// Change the last ',' '}':
Sb. setCharAt (sb. length ()-1 ,'}');
Return sb. toString ();
}

To process any Java Object in a unified manner, we compile an entry method toJson (Object) to encode any Java Object in JSON format:Copy codeThe Code is as follows: public static String toJson (Object o ){
If (o = null)
Return "null ";
If (o instanceof String)
Return string2Json (String) o );
If (o instanceof Boolean)
Return boolean2Json (Boolean) o );
If (o instanceof Number)
Return number2Json (Number) o );
If (o instanceof Map)
Return map2Json (Map <String, Object>) o );
If (o instanceof Object [])
Return array2Json (Object []) o );
Throw new RuntimeException ("Unsupported type:" + o. getClass (). getName ());
}

We did not strictly check Java objects. Unsupported objects (such as List) will directly throw a RuntimeException. In addition, to ensure that the output JSON is valid, the Key of the Map <String, Object> Object cannot contain special characters. Careful readers may also find that objects referenced cyclically lead to infinite recursion. For example, by carefully constructing a Map of cyclic references, StackOverflowException can be detected:Copy codeThe Code is as follows: @ Test (expected = StackOverflowError. class)
Public void testRecurrsiveMap2Json (){
Map <String, Object> map = new HashMap <String, Object> ();
Map. put ("key", map );
JsonUtil. map2Json (map );
}

Fortunately, the JSON data processed by the server should eventually be converted to simple JavaScript objects. Therefore, recursive reference is unlikely.
Finally, when outputting JSON data through Servlet or MVC framework, you must set the correct MIME type (application/json) and character encoding. Assuming that the server uses UTF-8 encoding, you can use the following code to output the encoded JSON text:Copy codeThe Code is as follows: response. setContentType ("application/json; charset = UTF-8 ");
Response. setCharacterEncoding ("UTF-8 ");
PrintWriter pw = response. getWriter ();
Pw. write (JsonUtil. toJson (obj ));
Pw. flush ();

Summary
JSON is already part of the JavaScript standard. Currently, mainstream browsers have excellent support for JSON. JSON can be used to parse XML. JSON is the most flexible lightweight solution for Web 2.0 websites that use Ajax.

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.