Use jQuery to simplify Ajax Development

Source: Internet
Author: User
Tags tojson unsupported
JSON Getting Started Guide


 

 

Level: elementary

Liao Xuefeng, author

August 22, 2008

JSON is JavaScript Object Natation. It is a lightweight data exchange format and is very suitable for server-to-JavaScript interaction. This article will quickly explain the JSON format and demonstrate how to process JSON format data on the client and server through code examples.

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"

Except characters",\,/And some controllers (\b,\f,\n,\r,\tOther 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 TypetrueOrfalse. In addition, null in JavaScript is expressednull, Note,true,falseAndnullNo 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:

{"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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.