Using newtonsoft. JSON;
Hashtable ht = new hashtable ();
Ht. Add ("AA", "1 ");
Ht. Add ("BB", "2 ");
String cc = javascriptconvert. serializeobject (HT );
Response. Write (CC );
Hashtable Tc = (hashtable) javascriptconvert. deserializeobject (CC, typeof (hashtable ));
String pp = tc ["AA"]. tostring ();
JSON Getting Started Guide (for details)
Original URL: http://www.ibm.com/developerworks/cn/web/wa-lo-json/
JSON is JavaScript Object Natation. It is a lightweight data exchange format and is very suitable for server-to-JavaScript interaction. This document describes the JSON format and usesCodeThe example shows how to process JSON format data on the client and server respectively.
Although there are many ideas about how XML has the cross-platform and cross-language advantages, unless it is applied to Web Services, in common web applications, developers often use their brains for XML parsing. Whether the server generates or processes XML, or the client uses JavaScript to parse XML, it often leads to complicated code and extremely low development efficiency. In fact, for most web applications, they do not need complicated XML to transmit data at all, and XML scalability is rarely advantageous. Many Ajax applications even directly return HTML fragments to build dynamic web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but at the same time lacks some flexibility.
JSON provides another data exchange format for Web application developers. Let's take a look at what JSON is. JSON provides better simplicity and flexibility than XML or HTML fragments.
JSON Data Format Parsing
Like XML, JSON is also based on plain text data format. Because JSON is designed for Javascript, The JSON data format is very simple. You can use JSON to transmit a simple string, number, or Boolean, or an array, or a complex object.
String, number, and Boolean are very simple in JSON format. For example, JSON represents a simple string "ABC" in the format:
Except characters"
,\
,/
And some controllers (\ B
,\ F
,\ N
,\ R
,\ T
Other Unicode characters can be output directly. Is a complete string representation structure:
Figure 1. Complete string representation structure
A number can be expressed as follows based on an integer or floating point:
Figure 2. Number representation structure
This corresponds to the vast majorityProgramming Language, For example:
12345 (integer) -3.9e10 (floating point number) |
Boolean TypeTrue
OrFalse
. In addition, null in Javascript is expressedNull
, Note,True
,False
AndNull
No double quotation marks. Otherwise, it will be treated as a string.
JSON can also represent an array object, using[]
Each element is separated by a comma. The element can be any value. For example, the following array contains a string, number, Boolean, and null:
["ABC", 12345, false, null] |
The object is in JSON{}
Contains a series of unordered key-value pairs. In fact, the object here is equivalentMap <string, Object>
Instead of Java class. Note that the 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) |
JSON format:
{& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025} |
Value can also be another object or array. Therefore, a complex object can be nested. For example, a person object contains the name and address objects, which can be expressed as follows:
{"Name": "Michael", "Address ": {& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025} } |
JavaScript processing JSON data
This section describes how to use JSON to represent data. Next, we also need to solve how to generate JSON-format data on the server to send data to the client, and how to use JavaScript to process JSON-format data on the client.
We will first discuss how to process JSON data in JavaScript on a web page. Using a simple JavaScript method, we can see how the client expresses JSON data to users:
Function handlejson (){ VaR J = {"name": "Michael", "Address ": {& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025} }; Document. Write (J. Name ); Document. Write (J. Address. City ); } |
Assume that the JSON data returned by the server is as follows:
{"Name": "Michael", "Address ": {& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025} } |
You only need to assign a value to a javascript variable to use the variable immediately and update the information on the page. JSON is easy to use than XML to read 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. Many Ajax frameworks already include the ability to process JSON data, such as prototype (a popular JavaScript Library: http://prototypejs.org) that providesEvaljson ()
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 output JSON format data
Next we will discuss how to output data in JSON format on the server side. Taking Java as an example, we will demonstrate how to encode a Java object as a JSON text.
When you encode a String object in JSON format, you only need to process special characters. In addition, you must use ("
) Instead ('
) Indicates 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 is much easier to express number as JSON. Using Java polymorphism, we can handle multiple number formats such as integer, long, and float:
Static string number2json (Number ){ Return number. tostring (); }
|
The boolean type can also be directly passed throughTostring ()
Method To Get The JSON representation:
Static string boolean2json (Boolean bool ){ Return bool. tostring (); }
|
To encode an array in JSON format, you can encode each element in 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 (','); } // Change the last ',' to ']': SB. setcharat (sb. Length ()-1, ']'); Return sb. tostring (); }
|
Finally, we needMap <string, Object>
The code is in JSON format, because the JavaScript Object actually corresponds to the JavaMap <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 ',' '}': SB. setcharat (sb. Length ()-1 ,'}'); Return sb. tostring (); }
|
To process arbitrary Java objects in a unified manner, we compile an entry method.Tojson (object)
To encode any Java object 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 did not strictly check Java objects. Unsupported objects (such as list) will directly throw a runtimeexception. In addition, to ensure that the output JSON is valid,Map <string, Object>
The object key cannot contain special characters. Careful readers may also find that the objects referenced by the loop will lead to infinite recursion. For example, by carefully constructing a Map referenced by the loop, we can detectStackoverflowexception
:
@ 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 converted to simple JavaScript objects. Therefore, recursive reference is unlikely.
Finally, when outputting JSON data through servlet or MVC framework, you must set the correct MIME type (Application/JSON) and character encoding. Assuming that the server uses UTF-8 encoding, you can use the following code to output the encoded JSON text:
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. Currently, mainstream browsers have excellent support for JSON. JSON can be used to parse XML. JSON is the most flexible lightweight solution for Web 2.0 websites that use Ajax.
Original URL: http://www.ibm.com/developerworks/cn/web/wa-lo-json/