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:
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:
{"city":"Beijing","street":" Chaoyang Road ","postcode":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 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) {<br/> stringbuilder sb = new stringbuilder (S. length () + 20); <br/> Sb. append ('"'); <br/> for (INT I = 0; I <S. length (); I ++) {<br/> char c = S. charat (I); <br/> switch (c) {<br/> case '"': <br/> Sb. append ("); <br/> break; <br/> case'': <br/> Sb. append (""); <br/> break; <br/> case '/': <br/> Sb. append ("/"); <br/> break; <br/> case 'B': <br/> Sb. append (""); <br/> break; <br/> case 'F': <br/> Sb. append ("F"); <br/> break; <br/> case 'N': <br/> Sb. append ("<br/>"); <br/> break; <br/> case 'r': <br/> Sb. append ("<br/>"); <br/> break; <br/> case 'T': <br/> Sb. append (""); <br/> break; <br/> default: <br/> Sb. append (c); <br/>}< br/> Sb. append ('"'); <br/> return sb. tostring (); <br/>}< br/>
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 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();
}
To encode an array in JSON format, you can encode each element in a loop:
Static String array2Json (Object [] array) {<br/> if (array. length = 0) <br/> return "[]"; <br/> StringBuilder sb = new StringBuilder (array. length <4); <br/> sb. append ('['); <br/> for (Object o: array) {<br/> sb. append (toJson (o); <br/> sb. append (','); <br/>}< br/> // change the last added ',' to ']': <br/> sb. setCharAt (sb. length ()-1, ']'); <br/> return sb. toString (); <br/>}</p> <p>
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) {<br/> if (map. isEmpty () <br/> return "{}"; <br/> StringBuilder sb = new StringBuilder (map. size () <4); <br/> sb. append ('{'); <br/> Set <String> keys = map. keySet (); <br/> for (String key: keys) {<br/> Object value = map. get (key); <br/> sb. append ('"'); <br/> sb. append (key); <br/> sb. append ('"'); <br/> sb. append (':'); <br/> sb. append (toJson (value); <br/> sb. append (','); <br/>}< br/> // change the last ',' to '}': <br/> sb. setCharAt (sb. length ()-1, '}'); <br/> return sb. toString (); <br/>}< br/>
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) {<br/> if (o = null) <br/> return "null"; <br/> if (o instanceof String) <br/> return string2Json (String) o); <br/> if (o instanceof Boolean) <br/> return boolean2Json (Boolean) o ); <br/> if (o instanceof Number) <br/> return number2Json (Number) o); <br/> if (o instanceof Map) <br/> return map2Json (Map <String, Object>) o); <br/> if (o instanceof Object []) <br/> return array2Json (Object []) o); <br/> throw new RuntimeException ("Unsupported type:" + o. getClass (). getName (); <br/>}
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();
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.