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:
Except characters"
,\
,/
And some controllers (\ B
,\ F
,\ N
,\ R
,\ T
Other Unicode characters can be output directly. 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 corresponds to the vast majorityProgramming Language, For example:
12345 (integer)-3.9e10 (floating point number) |
Boolean TypeTrue
OrFalse
. In addition, null in Javascript is expressedNull
, Note,True
,False
AndNull
No double quotation marks. Otherwise, it will be treated as a string.
JSON can also represent an array object, using[]
Each element is separated by a comma. 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 in JSON{}
Contains a series of unordered key-value pairs. In fact, the object here is equivalentMap <string, Object>
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": {"city": "Beijing", "street": "Chaoyang Road", "postcode": 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": {"city": "Beijing", "street": "Chaoyang Road ", "postcode": 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": {"city": "Beijing", "street": "Chaoyang Road", "postcode": 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 providesEvaljson ()
Method to 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, you must use ("
) Instead ('
) Indicates a string:
static string string2json (string s) {stringbuilder sb = new stringbuilder (S. length () + 20); sb. append ('\ "'); For (INT I = 0; I
|
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 passed throughTostring ()
Method To Get The JSON representation:
Static string boolean2json (Boolean bool) {return bool. tostring ();} |
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 added ',' to ']': Sb. setcharat (sb. length ()-1, ']'); return sb. tostring ();} |
Finally, we needMap <string, Object>
The code is in JSON format, because the JavaScript Object actually corresponds to the JavaMap <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 ',' to '}': Sb. setcharat (sb. length ()-1, '}'); return sb. tostring ();} |
To process arbitrary Java objects 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,Map <string, Object>
The object key cannot contain special characters. Careful readers may also find that the objects referenced by the loop will lead to infinite recursion. For example, by carefully constructing a Map referenced by the loop, we can detectStackoverflowexception
:
@ 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 the server uses UTF-8 encoding, you can use the followingCodeOutput 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 (); |
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.