Here we will derive json from the syntax of javascript, and based on this, how to use JSON in ajax applications.
Everyone knows that there is Arrays in javascript: array. Its format is as follows:
var Beatles = ["Paul" ,"John","George","Ringo"];
The above example is in the form of an Array and is equivalent to the following:
var Beatles =new Array ["Paul","John","George","Ringo"];
The other one is Objects. The way to create objects is as follows:
var Beatles = {"Country":"England","YearFormed":1959,"Style":"Rock'n'Roll"}
The above creation method is the same Create as follows:
var Beatles = new Object( );
Beatles.Country = "England";
Beatles.YearFormad = 1959;
Beatles.Style = "Rock'n'Roll";
Same as other javascript objects Similarly, attributes can be represented by '.' or '[ ]'.
Object can contain Array, as follows:
var Beatles = {
"Country" :"England",
"YeatFormed": 1959,
"Style" : "Rock'n'Roll",
"Members":[ "Paul"," John","George","Ringo"]
}
You can also include Objects in Array:
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"]
}
]
in JSON The official website describes JSON as follows:
1. A lightweight data conversion form
2. Easy for people to read and write.
3. Easy for machines to parse and generate.
JSON syntax. :
JSON may be difficult to read and write for some junior programmers, but it is still quite good for more experienced people (personal opinion)
Although the syntax of JSON and javascript are similar, each of them has similar syntax. An object cannot be assigned to a variable. That is, it is not an object but a string. We must use it through conversion every time we get JSON. Although the conversion can be achieved using the eval() function of JavaScript, for safety reasons. It is recommended that you use json.js for conversion. You can download it from the address provided above. The two most basic methods are:
JSON.parse(strJSON)-is used to convert JSON strings into JavaScript objects.
JSON.stringify(objJSON) – used to convert a JavaScript object into a JSON object.
This is data conversion on the client side, so how does it proceed on the server side? There are already very good conversion libraries for different languages. Because I am close to .net, here is how to use C# to perform server-side conversion of JSON.
I saw a foreign brother wrote a pretty good article on how to convert JSON under .net. It integrates JSON.NET and Microsoft's JavaScriptSerializer, so that no matter what format of JSON you have, you can basically handle it.
Now we provide a simple code for converting JSON, generating and parsing JSON:
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;
}
在NET.JSON的基础上使用JavascriptSeriazible来转换:
internal class WebExtensionsJavaScriptSerializer : JSONSerializerBase, IJSONSerializer
{
public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
{}
public string Serialize(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
List converters = new List();
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 SupportedTypes
{
get { return new Type[] {typeof (DataTable)}; }
}
public override object Deserialize(IDictionary dictionary, Type type,
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
下篇介绍如何在ASP.NET的环境下使用JSON和DataTable等的转换,还有介绍使用JQuery的AJAX调用Web Services的生成JSON、相当值得期待。^_^