JSON is JavaScript Object Natation. It is a lightweight data exchange format and is very suitable for server-to-JavaScript interaction. This document describes the JSON format and usesCodeThe example shows how to process JSON format data on the client and server respectively.
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.
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.
A number can be expressed as follows based on an integer or floating point:
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. 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 );
}
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:
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 ("http://www.cnblogs.com/rooney/admin/file:// B ");
Break;
Case '\ F ':
SB. append ("http://www.cnblogs.com/rooney/admin/file://f ");
Break;
Case '\ N ':
SB. append ("http://www.cnblogs.com/rooney/admin/file://n ");
Break;
Case '\ R ':
SB. append ("http://www.cnblogs.com/rooney/admin/file://r ");
Break;
Case '\ t ':
SB. append ("http://www.cnblogs.com/rooney/admin/file://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:
Static string number2json (Number ){
Return number. tostring ();
}
The boolean type can also be directly represented in JSON using the tostring () method:
static string boolean2json (Boolean bool) {
return bool. tostring ();
}< br> to encode an array in JSON format, you can encode each element in a loop:
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:
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:
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:
@ 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:
response. setcontenttype ("application/JSON; charset = UTF-8");
response. setcharacterencoding ("UTF-8");
printwriter PW = response. getwriter ();
PW. write (jsonutil. tojson (OBJ);
PW. flush ();
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.