JSON (II): JSON processing of the server side and the client

Source: Internet
Author: User
Tags tojson

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 start by looking at how the server outputs JSON format the Data bar.

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

<span style= "font-family:simhei;font-size:18px;"     >static Stringstring2json (String s) {StringBuilder SB = Newstringbuilder (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 (); }</span> 

It is much easier to represent number as JSON, and with Java polymorphism, we can deal with integer,long,float, and so on.

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >static Stringnumber2json (number number) {     return number.tostring ();  } </span>

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

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" > Static Stringboolean2json (Boolean bool) {     return bool.tostring ();  } </span>

To encode an array into JSON format, you can encode each element through a loop:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >static String Array2json (object[] array) {    if (array.length==0)         return "[]";     StringBuilder sb = Newstringbuilder (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 ();  } </span>

Finally, we need to map<string, object> encoded as JSON format, because JavaScript of the Object it actually corresponds to Java of the map<string, object> . The method is as follows:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" > Static Stringmap2json (map<string, object> Map) {     if (Map.isempty ())         return "{}";     StringBuilder sb = Newstringbuilder (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 ();  } </span>

The server side can now output data of various data types as JSON format, then how does the client accept and display the data? Let's take a look at how the client uses JavaScript to work with JSON -formatted data. assume that the JSON data returned by the server is the above:

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

We can see how the client will represent the JSON data to the user through a simple JavaScript method:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >function Handlejson () {   varj={"name": "Michael", "address":     {"City": "Beijing", "Street": "Chaoyangroad", "Postcode": 100025}  };   document.write (j.name);   document.write (j.address.city);  } </span>


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) with Evaljson () method to turn the JSON text returned by the server directly into a JavaScript variable:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >new ajax.request ("Http://url", {  method: "Get",   onsuccess:function (transport) {    var json = Transport.responseText.evalJSON ();    TODO:document.write (json.xxx);  }  }); </span>

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. Of course, this is only the most basic use, specific application to the project practice or need to carry out a variety of changes, first learn it.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JSON (II): JSON processing of the server side and the client

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.