JSON client and server-side format conversion _json

Source: Internet
Author: User
Here we'll derive json from the JavaScript syntax, and on that basis, how to use JSON on an AJAX application.
In JavaScript everybody knows there's a arrays: an array. Its format is as follows:
Copy Code code as follows:

var Beatles = ["Paul", "John", "George", "Ringo"];

The example above is the form of an array and the following equivalence:
Copy Code code as follows:

var Beatles =new Array ["Paul", "John", "George", "Ringo"];

One more is objects, and the object is created as follows:
Copy Code code as follows:

var Beatles = {"Country": "England", "yearformed": 1959, "Style": "Rock ' n ' Roll"}

The above creation method is equivalent to the following creation method:
Copy Code code as follows:

var Beatles = new Object ();
Beatles.country = "England";
Beatles.yearformad = 1959;
Beatles.style = "Rock ' n ' Roll";

As with other JavaScript objects, properties can pass '. ' or ' [] ' to represent it.
Object can contain an array, as follows:
Copy Code code as follows:

var Beatles = {
"Country": "England",
"Yeatformed": 1959,
"Style": "Rock ' n ' Roll",
"Members": ["Paul", "John", "George", "Ringo"]
}

You can also include objects in the array:
Copy Code code 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"
}
]

Describe JSON on the official web site as follows:
1. A lightweight form of data transformation.
2. Easy for people to read and write.
3. Easy machine to parse and generate.
The syntax for JSON:
JSON may be difficult for some junior programmers to read and write, but it's pretty good for more experienced people (personal opinion).
Although JSON and JavaScript have the same syntax, each of its objects cannot be assigned to a variable. That is, it is not a brother object but a string. Every time we get JSON, we have to use it by transformation. While the Eval () feature of JavaScript enables transformations, it is recommended that you use json.js for security purposes. Can be downloaded to the address provided above. There are two basic methods in it:
Json.parse (Strjson)-is used to convert JSON strings to JavaScript objects,
Json.stringify (Objjson) – Used to convert a JavaScript object to a JSON object.
This is the client's data transformation, then the server side how to do? For different languages there will be different already very good conversion libraries. Because I'm close to. NET, so here's how to use C # for server-side conversion of JSON.
I saw a foreign brother write an article about how to convert json under. NET is pretty good. He integrates json.net with Microsoft's JavaScriptSerializer so that no matter what format you're in, the JSON is basically done,
Now provides a simple conversion of JSON to generate and parse the JSON code:
Copy Code code 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 to convert on a net.json basis:
Copy Code code 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 transformations such as JSON and DataTable in a asp.net environment, as well as the generation JSON of Ajax invoke Web services using jquery, which is quite worth looking forward to. ^_^

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.