While there is a lot of hype about how XML has cross-platform, cross-language benefits, unless applied to web Services, developers often have a headache with parsing XML, whether it's server-side generation or processing of XML, or client JavaScript parsing XML often leads to complex code and very low development efficiency. In fact, for most Web applications, they don't need complex XML to transmit data at all, and XML extensibility is rarely an advantage, and many AJAX applications even return HTML fragments directly to build dynamic Web pages. Returning HTML fragments greatly reduces the complexity of the system compared to returning XML and parsing it, but at the same time lacks some flexibility.
Now, JSON provides another form of data interchange for WEB app developers. Let's take a look at what JSON is, and JSON provides better simplicity and flexibility than XML or HTML fragments.
JSON Data Format parsing
As with XML, JSON is also a data format based on plain text. Since JSON is inherently prepared for JavaScript, the JSON data format is very simple, you can transfer a simple string,number,boolean with JSON, or you can transfer an array, or a complex object.
String,number and Boolean representations of JSON are very simple. For example, use JSON to represent a simple String "ABC" in the form of:
"abc"
In addition to the character ",/and some control characters (b,f,n,r,t) need to be encoded, other Unicode characters can be output directly.
A number can be represented by an integer or floating-point number as follows:
This is consistent with the representation of most programming languages, such as:
12345(整数)
-3.9e10(浮点数)
The Boolean type is expressed as true or false. In addition, NULL in JAVASCRIPT is represented as NULL, and note that true, FALSE, and null do not have double quotes, otherwise they will be treated as a String.
JSON can also represent an array object, using [] contains all elements, each element is separated by commas, and the element can be any Value, for example, the following array contains a string,number,boolean and a null:
["abc",12345,false,null]
Object objects are represented in JSON with a series of unordered Key-value key-value pairs, in fact the object here is equivalent to map<string in Java, Object>, rather than Java Class. Note that Key can only be represented by String.
For example, an Address object contains the following key-value:
city:Beijing
street:Chaoyang Road
postcode:100025(整数)
This is represented by JSON:
{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
Where Value can also be another object or an array, complex objects can be nested representations, for example, a person object that contains a name and address object, which can be represented as follows:
{"name":"Michael","address":
{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
}
JavaScript 处理 JSON 数据
The above describes how to represent data in JSON, and then we will also work out how to generate JSON-formatted data on the server side for sending to the client, and how the client uses JavaScript to process data in JSON format.
Let's discuss how to process JSON data in a Web page with JavaScript. We can see how the client will represent the JSON data to the user through a simple JavaScript method:
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 the above:
{"name":"Michael","address":
{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
}
By simply assigning it to a JavaScript variable, you can immediately use the variable and update the information in the page, which is very easy to use when the XML needs to read the 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. There are many Ajax frameworks that already contain the ability to process JSON data, such as Prototype (a popular JavaScript library: http://prototypejs.org) that provides a Evaljson () method that directly returns JSON text to 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);
}
});
服务器端输出 JSON 格式数据
Here we discuss how to output JSON-formatted data on the server side. In Java, for example, we will demonstrate the encoding of a Java object into JSON-formatted text.
When you encode a String object in JSON format, you only need to handle the special characters. In addition, the string must be represented by (") rather than ('):
[Java]View PlainCopy
- 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 ("");
- Break
- Case ' F ':
- Sb.append ("F");
- Break
- Case ' n ':
- Sb.append ("
- ");
- Break
- Case ' R ':
- Sb.append ("
- ");
- Break
- Case ' t ':
- Sb.append ("");
- Break
- Default
- Sb.append (c);
- }
- }
- Sb.append (' "');
- return sb.tostring ();
- }
It is much easier to represent number as JSON, and with Java polymorphism, we can deal with integer,long,float, and so on.
static String number2Json(Number number) {
return number.toString();
}
The Boolean type can also get the JSON representation directly through the ToString () method:
static String boolean2Json(Boolean bool) {
return bool.toString();
}
To encode an array into JSON format, you can encode each element through a loop:
[Java]View PlainCopy
- 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 (', ');
- }
- The last added ', ' becomes '] ':
- Sb.setcharat (Sb.length ()-1, '] ');
- return sb.tostring ();
- }
Finally, we need to encode map<string, object> into JSON format, because JavaScript Object actually corresponds to Java map<string, object>. The method is as follows:
[Java]View PlainCopy
- 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 ();
- }
为了统一处理任意的 Java 对象,我们编写一个入口方法 toJson(Object),能够将任意的 Java 对象编码为 JSON 格式:
[Java]View PlainCopy
- 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 do not have strict checks on Java objects. Objects that are not supported (such as List) will throw runtimeexception directly. In addition, to ensure that the output JSON is valid, map<string, the Object> object's Key cannot contain special characters. The attentive reader may also find that the loop-referenced object throws infinite recursion, for example, by carefully constructing a circular-referenced Map, the 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 into simple JavaScript objects, so the likelihood of recursive referencing is minimal.
Finally, when you output JSON through a Servlet or MVC framework, you need to set the correct MIME type (Application/json) and character encoding. Assuming that the server uses UTF-8 encoding, you can output the encoded JSON text using the following code:
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, the mainstream browser is perfect for JSON support. Using JSON, we can get rid of the parsing of XML, and for those Web 2.0 Web sites that apply Ajax, JSON is really the most flexible lightweight solution available today.
Getting Started with JSON tutorial