JSON Getting Started Guide

Source: Internet
Author: User
Tags control characters tojson

JSON, or JavaScript Object natation, is a lightweight data interchange format that is ideal for server-to-javascript interaction. This article will quickly explain the JSON format and demonstrate how to handle JSON-formatted data on both the client and server side, using code examples.

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.

SON 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 characters " , \ / and some control characters (,,,, \b \f ) need to be \n \r \t encoded outside, other Unicode characters can be output directly. is a complete representation structure of a String:

Figure 1. Full representation structure of String

A number can be represented by an integer or floating-point number as follows:

Figure 2. The representation structure of number

This is consistent with the representation of most programming languages, such as:

12345 (integer) -3.9e10 (floating point)

The Boolean type is expressed as true or false . In addition, NULL in JavaScript is represented as null , note, and none of the true false null double quotes, otherwise it will be treated as a String.

JSON can also represent an array object, with [] all the elements, each element 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 Java Map<String, Object> , not 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 (integer)

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 Processes JSON Data

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) evalJSON() that provides a way to directly convert the JSON text returned by the server into a J Avascript variables:

New Ajax.request ("Http://url", {   method: "Get",   onsuccess:function (transport) {     var json = Transport.responseText.evalJSON ();     TODO:document.write (json.xxx);   }  });
Server-side output JSON format data

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 ( ):

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 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 be used to toString() get the JSON representation directly from the method:

Static String Boolean2json (Boolean bool) {     return bool.tostring ();  }

To encode an array into JSON format, you can encode each element through 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 (', ');     }     The last added ', ' changed to '] ':     Sb.setcharat (Sb.length ()-1, '] ');     return sb.tostring ();  }

Finally, we need to Map<String, Object> encode it in JSON format, because the JavaScript Object actually corresponds to Java Map<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 (', ');     }     Turn the last ', ' to '} ':     Sb.setcharat (Sb.length ()-1, '} ');     return sb.tostring ();  }

To unify the processing of arbitrary Java objects, we write an ingress method toJson(Object) that encodes any Java object into 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 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, the Map<String, 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 Map with a circular reference, you can detect StackOverflowException :

@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.

Transferred from: http://www.ibm.com/developerworks/cn/web/wa-lo-json/

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.