[JSON] JSON Getting Started Guide __json

Source: Internet
Author: User
Tags control characters tojson
reproduced from: http://www.ibm.com/developerworks/cn/web/wa-lo-json/index.html

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

Although there is a lot of publicity about how XML has cross-platform, Cross-language advantages, however, unless applied to web Services, developers often have a brain for XML parsing in ordinary Web applications, whether it's server-side generation or processing XML, or client JavaScript parsing XML, often leads to complex code, very low development efficiency. In fact, for most Web applications, they do not need complex XML to transmit data, XML extensibility has little advantage, and many AJAX applications even directly return HTML fragments to build dynamic Web pages. As opposed to returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but at the same time lacks some flexibility.

Now, JSON provides another form of data interchange for WEB application developers. Let's look at what JSON is, and JSON provides better simplicity and flexibility than XML or HTML fragments.


JSON data Format parsing

Like XML, JSON is a data format based on plain text. Because JSON is inherently prepared for JavaScript, JSON's 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 are very simple to represent in JSON. For example, use JSON to represent a simple String "ABC" in the form of:

"ABC"

Except for characters ", \,/and some control characters (\b,\f,\n,\r,\t) require encoding, other Unicode characters can be directly exported. The following figure is the complete representation structure of a String: figure 1. The complete representation structure of a 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 number)

Boolean type is represented as true or false. In addition, NULL in JAVASCRIPT is represented as NULL, noting 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 [] to contain 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 in JSON are represented by {} containing 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 the Key can only be represented by a String.

For example, an Address object contains the following key-value:

City:beijing 
 Street:chaoyang Road 
 postcode:100025 (integer)

The following is represented in 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 contains the name and address objects, which can be represented as follows:

{"Name": "Michael", "Address":
    {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}
}
JavaScript processing JSON data

It shows how to represent data in JSON, and then we'll work out how to generate JSON-formatted data on the server side to send to the client, and how the client uses JavaScript to process data in JSON format.

Let's first discuss how to process JSON data in a Web page using JavaScript. Using a simple JavaScript approach, we can see how the client represents the JSON data to the user:

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 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 on the page, which is easy to use when compared to the XML need to read various nodes from the DOM. All we need to do is send an AJAX request and then 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) provides a Evaljson () method that directly returns the JSON text of 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-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 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's much easier to represent number as JSON, and with Java polymorphism, we can handle several number formats such as Integer,long,float:

Static String Number2json (number number) {return 
    number.tostring (); 
 }

A Boolean type can also get the representation of JSON directly through the ToString () method:

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

To encode an array in JSON format, you can encode each of the elements by looping:

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 (', '); 
    } 
    Add the last ', ' into '] ': 
    Sb.setcharat (Sb.length ()-1, '] '); 
    return sb.tostring (); 
 }

Finally, we need to encode map<string, object> into 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) { 
    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 final ', ' into '} ': 
    Sb.setcharat (Sb.length ()-1, '} '); 
    return sb.tostring (); 
 }

To unify the processing of any Java object, we write an entry 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 a rigorous examination of 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 Key of the Object> object cannot contain special characters. Attentive readers may also find that a circular reference can cause infinite recursion, for example, by carefully constructing a loop-referenced Map that detects 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 translated into a simple JavaScript object, so the likelihood of recursive references is small.

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 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. At present, the mainstream browser support for JSON is very perfect. Using JSON, we can get rid of XML parsing, and for those Web 2.0 Web sites that use Ajax, JSON is really the most flexible lightweight solution.

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.