What is JSON? Data format prepared for JavaScript
Not yet understand what JSON is? After reading this article, you should be able to have a clearer idea of what JSON is.
JSON is JavaScript. Object Natation, which is a lightweight data interchange format, is well suited for server and JavaScript. The 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.
JSON Data Format parsing
As with XML, JSON is also a data format based on plain text. Because JSON is inherently JavaScript-only. Prepared, therefore, the JSON data format is very simple, you can transfer a simple string,number,boolean with JSON, you can also 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 the characters ", \,/and some control characters (\b,\f,\n,\r,\t) need to be encoded, other Unicode characters can be output directly.
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, JavaScript. The null in is represented as NULL, and note 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 [] contains all elements, each element is 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 map<string in Java, Object>, rather than 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. Working with 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 to send to the client and how the client uses JavaScript. Processes data in JSON format.
Let's discuss how to work with JavaScript in Web pages. Process JSON data. We pass a simple JavaScript. method to see how the client can 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}
- }
Just assign 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) provides the Evaljson () 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-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 get the JSON representation directly through the ToString () 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 ', ' becomes '] ':
- Sb.setcharat (Sb.length ()-1, '] ');
- return sb.tostring ();
- }
Finally, we need to encode map<string, object> into JSON format because of JavaScript. The 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 (', ');
- }
- //Change 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, map<string, the 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 circular-referenced Map, the StackOverflowException can be detected:
- @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 simple JavaScript. object, so the likelihood of a recursive reference 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 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 JavaScript. Part of the 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.
What is JSON, now you should know it.
What is JSON? Data format prepared for JavaScript