Format conversion between the JSON client and the server

Source: Internet
Author: User
Tags javascript eval

Here we will extend json from the javascript syntax and introduce how to use JSON in ajax applications.
As you know in javascript, there is an Arrays: array. The format is as follows:
Copy codeThe 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 codeThe Code is as follows:
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 codeThe Code is as follows:
Var Beatles = {
"Country": "England ",
"YeatFormed": 1959,
"Style": "Rock 'n' Roll ",
"Members": ["Paul", "John", "George", "Ringo"]
}

You can also include Objects in Array:
Copy codeThe Code is as follows:
Var Rockbands = [
{
"Name": "BeatLes ",
"County": "England ",
"YearFormed": 1959,
"Style": "Rock 'n' Roll ",
"Members": ["Paul", "John", "George", "Ringo"]
},
{
"Name" "Rolling Stones ",
"Country": "England ",
"YearFormed": 1962,
"Style": "Rock 'n' Roll ",
"Members": ["Mick"], "Keith", "Charlie", "Bill"]
}
]

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 eldest brother wrote a very good article about how to convert JSON in. net. 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 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. Pai_^

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.