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 is consistent with the representation of the vast majority of programming languages, such:
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:
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:
{"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 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<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:
static String number2Json(Number 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 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.