JSON Parsing data format

Source: Internet
Author: User
Tags control characters tojson

April 26, 2014 This 10:55:15 starts from the beginning of March, and the JSON fights. The school does not teach how to do, oneself. Large-scale search AH. Post This article, like me and don't know how to start a newbie!


and XML such as. JSON is also based on a plain text data grid formula. JSON is inherently prepared for JavaScript. So. JSON data format is easy, you can use JSON to transfer a simple string,number,boolean, you can also transfer an array, or a complex object objects.

String. The number and Boolean expressions 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 the character ", \,/and some control characters (\b,\f,\n. \r,\t) need to be encoded, 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 expressed as true or false. In addition, NULL in JAVASCRIPT is represented as NULL, note. Both true, FALSE, and Null have no double-quotes. Otherwise it will be treated as a String.
JSON can also represent an array object, using [] including all elements. Each element is separated by a comma, and the element can be arbitrary Value, for example, the following array includes a string,number,boolean and a null:

["ABC", 12345,false,null]

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


Object objects in JSON are represented by {} including 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 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

Demo sample with JSON table for example the following:

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


Value can also be an Object or an array. So. Complex objects can be nested representations, such as a person object that includes the name and address objects, and can 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 use JSON to represent data, and then we will also 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}}

You just need to assign it to a JavaScript variable. will be able to immediately use the variable and update the information in the page, compared to the XML need to read from the DOM of the various nodes. The use of JSON is very

Easy. What we need to do, however, is to send an AJAX request. You can 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 a Evaljson () method that directly returns the server to the The JSON text becomes a JavaScript variable:


New Ajax.request ("Http://url", {method: "Get", onsuccess:function (transport) {var json = Transport.responseText.evalJS On (); 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 have to deal with 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 (" \\\\ "); /': 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 is also able to get the JSON representation directly through the ToString () method:
Static String Boolean2json (Boolean bool) {return bool.tostring ();}
You want to encode the array in JSON format. It is possible to 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 (', ');}//Will add last ', ' into '] ': Sb.setcharat (Sb.len Gth ()-1, '] '); return sb.tostring (); }
At last. We need to encode map<string, object> into JSON format. Since JavaScript's Object is actually corresponding to Java's 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 (': '); s B.append (ToJson (value)); Sb.append (', '); }//Will last ', ' into '} ': Sb.setcharat (Sb.length ()-1, '} '); return sb.tostring (); }
To handle arbitrary Java objects uniformly. We write an Ingress method ToJson (object), which encodes random Java objects 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, map<string, the Key of the Object> object cannot include special characters. The attentive reader may also find that the object being referenced by the loop throws infinite recursion, for example. By carefully structuring a Map with a circular reference, you can detect the 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. For now, the mainstream browser is in good condition for JSON support. Using JSON, we can get rid of the parsing of XML. For WEB 2.0 sites that apply Ajax, JSON is really the most flexible lightweight solution at the moment.

This is what I have from the PDF, if it is not convenient to see my resources to download!

JSON data grid formulas. pdf



Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

JSON Parsing data format

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.