Format conversion between the JSON client and the server

Source: Internet
Author: User
Tags javascript eval

Here we will extend the JSON from the Javascript syntax, and then introduce how to apply Program Use JSON.
As you know in Javascript, there is an arrays: array. The format is as follows: CopyCode The Code is as follows: var Beatles = ["PAUL", "John", "George", "ringo"];

The array format of the above instance is equivalent to the following:Copy codeThe Code is as follows: var Beatles = new array ["PAUL", "John", "George", "ringo"];

The other one is objects. The object creation method is as follows:Copy codeCode: var Beatles = {"country": "England", "yearformed": 1959, "style": "rock 'n' roll "}

The above creation method is equivalent to the following creation method:Copy codeThe Code is as follows: var Beatles = new object ();
Beatles. Country = "England ";
Beatles. yearformad = 1959;
Beatles. Style = "rock 'n' roll ";

Like other JavaScript objects, attributes can be expressed by '.' or.
An object can contain an array, as shown below:Copy codeCode: var Beatles = {
"Country": "England ",
"Yeatformed": 1959,
"Style": "rock 'n' roll ",
"Members": ["Paul", "John", "George", "Ringo"]
}

You can also include objects in array: copy Code the code is as follows: var rockbands = [
{< br>" name ":" Beatles ",
"County": "England",
"yearformed": 1959,
"style": "rock 'n' roll ",
"members": ["PAUL", "John", "George", "ringo"]
},
{< br> "name" "Rolling Stones",
"country": "England",
"yearformed": 1962,
"style": "rock 'n' roll",
"members": ["Mick"], "Keith", "Charlie ", "Bill"]
}< br>]

JSON is described on the official JSON website as follows:
1. A lightweight data conversion form.
2. It is easy for people to read and write data.
3. Easy machine resolution and generation.
JSON Syntax:
JSON may be hard to read and write for some junior programmers, but it is quite good for experienced people (personal opinion ).
Although the syntax of JSON and JavaScript is similar, each of its objects cannot be assigned a variable. That is, it is not a brother object but a string. Every time we get the JSON, we must use it through conversion. Although Javascript eval () can be used for conversion, we recommend that you use JSON. js for security reasons. You can download from the address provided above. There are two basic methods in it:
JSON. parse (strjson)-is used to convert a JSON string to a JavaScript Object,
JSON. stringify (objjson)-used to convert a javascript object into a JSON object.
This is the data conversion from the client. How can this problem be performed on the server? Different conversion libraries are available for different languages. Because I am close to. net, I will introduce how to use C # For JSON server-side conversion.
I think a foreign big brother wrote an article about how to convert JSON in. net.ArticlePretty good. He integrated JSON. Net with Microsoft's javascriptserializer, so that no matter which format of JSON you are using,
A simple code for generating and parsing JSON is provided:Copy codeThe Code is as follows: Public String serialize (object value)
{
Type type = value. GetType ();

Newtonsoft. JSON. jsonserializer JSON = new newtonsoft. JSON. jsonserializer ();

JSON. nullvaluehandling = nullvaluehandling. Ignore;

JSON. objectcreationhandling = newtonsoft. JSON. objectcreationhandling. Replace;
JSON. missingmemberhandling = newtonsoft. JSON. missingmemberhandling. Ignore;
JSON. referenceloophandling = referenceloophandling. Ignore;

If (type = typeof (datarow ))
JSON. converters. Add (New datarowconverter ());
Else if (type = typeof (datatable ))
JSON. converters. Add (New datatableconverter ());
Else if (type = typeof (Dataset ))
JSON. converters. Add (New datasetconverter ());

Stringwriter Sw = new stringwriter ();
Newtonsoft. JSON. jsontextwriter writer = new jsontextwriter (SW );
If (this. formatjsonoutput)
Writer. Formatting = formatting. indented;
Else
Writer. Formatting = formatting. None;

Writer. quotechar = '"';
JSON. serialize (writer, value );

String output = Sw. tostring ();
Writer. Close ();
Sw. Close ();

Return output;
}

Public object deserialize (string jsontext, type valuetype)
{
Newtonsoft. JSON. jsonserializer JSON = new newtonsoft. JSON. jsonserializer ();

JSON. nullvaluehandling = newtonsoft. JSON. nullvaluehandling. Ignore;
JSON. objectcreationhandling = newtonsoft. JSON. objectcreationhandling. Replace;
JSON. missingmemberhandling = newtonsoft. JSON. missingmemberhandling. Ignore;
JSON. referenceloophandling = newtonsoft. JSON. referenceloophandling. Ignore;

Stringreader sr = new stringreader (jsontext );
Newtonsoft. JSON. jsontextreader reader = new jsontextreader (SR );
Object result = JSON. deserialize (reader, valuetype );
Reader. Close ();

Return result;
}

Use javascriptseriazible for conversion based on net. JSON:Copy codeThe Code is as follows: internal class webextensionsjavascriptserializer: jsonserializerbase, ijsonserializer
{
Public webextensionsjavascriptserializer (jsonserializer serializer): Base (serializer)
{}

Public String serialize (object value)
{
Javascriptserializer SER = new javascriptserializer ();

List <javascriptconverter> converters = new list <javascriptconverter> ();

If (value! = NULL)
{
Type type = value. GetType ();
If (type = typeof (datatable) | type = typeof (datarow) | type = typeof (Dataset ))
{
Converters. Add (New webextensionsdatarowconverter ());
Converters. Add (New webextensionsdatatableconverter ());
Converters. Add (New webextensionsdatasetconverter ());
}

If (converters. Count> 0)
Ser. registerconverters (converters );
}

Return = Ser. serialize (value );
}
Public object deserialize (string jsontext, type valuetype)
{
// *** Have to use reflection with a 'dynamic 'non constant type instance
Javascriptserializer SER = new javascriptserializer ();

Object result = Ser. GetType ()
. Getmethod ("deserialize ")
. Makegenericmethod (valuetype)
. Invoke (SER, new object [1] {jsontext });
Return result;
}
}

Internal class webextensionsdatatableconverter: javascriptconverter
{
Public override ienumerable <type> supportedtypes
{
Get {return New Type [] {typeof (datatable )};}
}

Public override object deserialize (idictionary <string, Object> dictionary, type,
Javascriptserializer serializer)
{
Throw new notimplementedexception ();
}

the next article describes how to use JSON and able conversions in the ASP. NET environment, as well as how to use jquery ajax to call web services to generate JSON, which is quite worth looking forward. ^ _ ^

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.