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 explain the JSON format at high speed. The Code demonstration sample demonstrates how to handle the JSON format data separately on the client and server side.

While there's a lot of hype about how XML has cross-platform. Cross-language advantage. However. Unless applied to Web Services. Otherwise, in a normal WEB application. Developers often have a headache with parsing XML, whether it's server-side generation or processing of XML, or client parsing XML with JavaScript. Often lead to complex code, very low development efficiency.

In fact, for most Web applications, they do not need complex XML for data transfer, XML has very little extensibility, and many AJAX applications even return HTML fragments directly to build dynamic Web pages. Returning HTML fragments greatly reduces the complexity of the system, but lacks some flexibility at the same time, compared to returning XML and parsing it.

Today, JSON provides WEB application developers with a data interchange format.

Let's look at what JSON really is. Compared with XML or HTML fragments. JSON provides greater simplicity and flexibility.


Ajax Resource Center

Please visit the Ajax Resource Center. This is a one-stop center for information about the Ajax programming model, with a lot of documentation, tutorials, forums, blogs, wikis, and news. No matter what the new Ajax information can be found here.


JSON Data Format parsing

As with XML, JSON is also a data format based on plain text. Because JSON is inherently prepared for JavaScript, the JSON data format is easy, you can transfer a simple string,number,boolean with JSON, you can transfer an array, or a complex object.

String,number and Boolean are very easy to use with JSON.

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

\ n

\ r

\ t
), 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 perform a sample based on an integer or floating point number such as the following:


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 represented as
True
Or
False

In addition, NULL in JavaScript is represented as
Null
Attention
True

False
And
Null
There are no double-quotes, otherwise it will be treated as a String.

JSON can also represent an array object, using the
[]
Including all elements, each element is separated by commas, the element can be arbitrary Value, for example, the following array includes a string,number,boolean and a null:


["ABC", 12345,false,null]

Object objects are used in JSON
{}
Consists of a series of unordered Key-value key-value pairs, in fact the Object here is equivalent to that in Java
Map<string, object>
, not Java's Class. Note that Key can only be represented by String.

For example, an Address object includes such as the following key-value:


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

Demo sample with JSON table for example the following:


{"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}

The Value can also be an Object or an array, so. Complex objects can be nested representations, such as. A Person object includes the name and address objects and is able to perform samples such as the following:


{"Name": "Michael", "Address":    {"City": "Beijing", "Street": "Chaoyang Road", "Postcode": 100025}}

JavaScript Processes JSON Data

The above describes how to represent data in JSON. Next. We also need to 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 discuss how to work with JSON data in a Web page using JavaScript. With a simple JavaScript approach, we can see how the client will represent 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 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, and JSON is easy to use compared to the XML needs to read the various nodes from the DOM. What we need to do is to send an AJAX request and then assign the JSON data returned by the server to a variable. There are many Ajax frameworks that already include the ability to process JSON data, such as Prototype (a popular JavaScript library: http://prototypejs.org) that provides
Evaljson ()
method, you can 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-side output JSON format data

Below we discuss how to output JSON-formatted data on the server side. Take Java as an example. We will demonstrate the encoding of a Java object into JSON-formatted text.

When you encode a String object in JSON format, you just need to handle the special characters. In addition, you must use (
"
) rather than (

) Represents 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's much more easy to represent number as JSON, and with Java polymorphism, we can handle multiple number formats such as Integer,long,float:


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

The Boolean type can also be passed directly through the
ToString ()
method to get the JSON representation:


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

Finally, we need to
Map<string, object>
Encoded in JSON format, because JavaScript Object is actually corresponding 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 handle random Java objects uniformly, we write an entry method
ToJson (Object)
。 Arbitrary Java objects can be encoded 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 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, object>
The object's Key cannot also include special characters. The attentive reader may also find that the object being referenced by the loop throws infinite recursion, such as constructing a Map with a circular reference. To be able to 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 finally be translated into simple JavaScript objects. So. The likelihood of recursive referencing is very 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 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. Now. The mainstream browser supports JSON support in good condition. Using JSON, we can get rid of XML parsing, for those WEB 2.0 sites that apply Ajax. JSON is really the most flexible lightweight solution at the moment.

JSON Getting Started Guide

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.