The full name of JSON is "JavaScript Object Notation", which means the JavaScript objects notation, which is a text-based, language-independent, lightweight data interchange format. XML is also a data interchange format, why not choose XML? Since XML can be used as a cross-platform data interchange format, it is very inconvenient to process XML in JS (abbreviated JavaScript), while XML tags are much more than data, which increases the traffic generated by the interchange, and JSON does not have any tags attached to it, which can be treated as objects in JS. So we are more inclined to choose JSON to exchange data. This article explains JSON mainly from the following aspects.
Two kinds of structure of 1,json
2, recognize the JSON string
3, how to use JSON in JS
4, in. How to use JSON in net
5, summary
Two kinds of structure of JSON
JSON has two representations of structures, objects, and arrays.
The object structure starts with "{" Curly braces and ends with "}" curly braces. The middle section consists of 0 or more "key (key)" pairs consisting of "," separated by "/value", the keywords and values separated by ":", and the grammatical structure such as code.
{ key1:value1, key2:value2, ...}
Where the keyword is a string, and the value can be a string, a value, a true,false,null, an object, or an array
The array structure ends with "[" Start, "]". The middle consists of 0 or more lists of values separated by ",", grammatical structures such as code.
[ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }]
Recognize JSON strings
I've been confused before, and I can't tell the difference between a normal string, a JSON string, and a JSON object. After some research, I finally figured it out. For example, in JS.
String: This is a good explanation for the use of "" "double quotation marks or single quotation marks to include characters. For example: var comstr = ' This is string ';
JSON string: Refers to a JS string that conforms to the JSON format requirements. For example: var jsonstr = "{studentid: '", Name: ' Tmac ', Hometown: ' USA '} ";
JSON object: Refers to a JS object that conforms to the JSON format requirements. For example: var jsonobj = {studentid: "", "Name:" Tmac ", Hometown:" USA "};
How to use JSON in JS
JSON is a subset of JS, so it is easy to read and write JSON in JS. There are two ways to read and write JSON, respectively, using "." operator and the "[Key]" method.
We first define a JSON object, the code is as follows.
var obj = { 1: "Value1", "2": "value2", 3, // array structure JSON object that can be nested using { 1, "Zhang San" }, { 2, "John Doe" } ], // Object Structure JSON object id:1, "object in Object" } };
1, reading data from JSON
function Readjson () { alert (obj.// will report a syntax error, you can use alert (obj["1"]); it's best not to do the keyword // Ibid . alert (obj.person[// or alert (obj.person[0]["name"]) // or alert (obj.object["MSG"]) }
2. Write data to JSON
For example, to add a piece of data to the JSON, the code is as follows:
function Add () { // adds a record to the JSON object // or obj["sex"]= "male" }
JSON object after adding data
3. Modify the data in the JSON
We are now going to modify the value of count in JSON as follows:
function Update () { // or obj["Count"]=10 }
The modified JSON.
4. Delete data from JSON
We now implement the deletion of the count from JSON data, the code is as follows:
function Delete () { delete obj.count; }
Post-Deletion JSON
You can see that count has been removed from the JSON object.
5, traversing the JSON object
You can use for...in ... Loop to iterate through the data in the JSON object, for example, we want to traverse the value of the output obj object, the code is as follows:
function traversal () { for (var in obj) { + ": ", Obj[c]) ; } }
The program output results are:
How to use JSON in. Net
When it comes to using JSON in. NET, you have to mention Json.NET, which is a very well-known tool for working with JSON in. NET, the following two features are most commonly used.
1. Convert. NET objects to JSON strings by serialization
In the Web development process, we often need to convert the data from the database (typically a collection, a list or an array, etc.) to a JSON format string back to the client, which needs to be serialized, here is the SerializeObject method of the JsonConvert object. Its syntax is Jsonconvert.serializeobject (object), and "Object" in the code is the. NET object to serialize, and the JSON string is returned after serialization.
For example, now we have a tstudent student table, the fields in the table and the existing data
From the table we can see a total of five data, now we want to extract the data from the database, and then use the Json.NET JsonConvert object to serialize them as a JSON string, and displayed on the page. C # code is as follows
protected voidPage_Load (Objectsender, EventArgs e) { using(L2sdbdatacontext db =NewL2sdbdatacontext ()) {List<Student> studentlist =NewList<student>(); varquery = fromSinchdb. TstudentsSelect New{StudentID=S.studentid, Name=S.name, Hometown=S.hometown, Gender=S.gender, Brithday=S.birthday, ClassID=S.classid, Weight=S.weight, Height=S.height, Desc=S.desc}; foreach(varIteminchquery) {Student Student=NewStudent {Studentid=item. Studentid,name=item. Name,hometown=item. Hometown,gender=item. Gender,brithday=item. Brithday,classid=item. Classid,weight=item. Weight,height=item. Height,desc=item. DESC}; Studentlist.add (student); } Lbmsg.innertext=Jsonconvert.serializeobject (studentlist); } }
Output results
We can see that the 5 records in the database are all taken out and converted into JSON strings.
2. Customizing JSON Data Using LINQ to JSON
Using the JsonConvert object's serializeobject simply converts a list or collection to a JSON string. However, sometimes our front-end framework such as EXTJS for the data format returned by the server has certain requirements, such as the following data format, then need to use Json.NET LINQ to Json,linq to JSON function is to customize the JSON data according to the format required.
For example, the JSON format, often used in pagination, is as code:
{ / / Total records "Rows": data list in JSON format ]}
Before using LINQ to Json, you need to reference the Newtonsoft.json DLL and the namespace of the using Newtonsoft.Json.Linq. LINQ to JSON mainly uses four objects, Jobject, Jarray, Jproperty, and Jvalue, Jobject is used to generate a JSON object, simply to generate "{}", Jarray to generate a JSON array, that is, "[] ", Jproperty is used to generate a JSON data in the form of a key/value value, while Jvalue generates a JSON value directly. Here we will return the data in the page format using LINQ to JSON. The code is as follows:
protected voidPage_Load (Objectsender, EventArgs e) { using(L2sdbdatacontext db =NewL2sdbdatacontext ()) { //fetch data from the database and place it in listList<student> studentlist =NewList<student>(); varquery = fromSinchdb. TstudentsSelect New{StudentID=S.studentid, Name=S.name, Hometown=S.hometown, Gender=S.gender, Brithday=S.birthday, ClassID=S.classid, Weight=S.weight, Height=S.height, Desc=S.desc}; foreach(varIteminchquery) {Student Student=NewStudent {StudentID = Item. StudentID, Name = Item. Name, Hometown = Item. Hometown, Gender = Item. Gender, Brithday = Item. Brithday, ClassID = Item. ClassID, Weight = Item. Weight, Height = Item. Height, Desc =item. DESC}; Studentlist.add (student); } //Create JSON data in the desired format using LINQ to JSON based on the list createdLbmsg.innertext =NewJobject (NewJproperty (" Total", Studentlist.count),NewJproperty ("rows", NewJarray (//using LINQ to JSON, you can generate JSON data objects directly in the SELECT statement without the need for additional conversion procedures fromPinchstudentlistSelect NewJobject (NewJproperty ("StudentID", P.studentid),NewJproperty ("name", p.name),NewJproperty ("Hometown", P.hometown)) ) ) ). ToString (); } }
The output is:
3, processing the JSON data submitted by the client
The data submitted by the client is typically a JSON string with a better operation (object-oriented approach), so we will generally try to convert the JSON string to a JSON object. For example, the client submits the following array format JSON string.
[ {studentid:"+", Name: "AAA", Hometown: "China"}, {studentid:"101", Name: "BBB", Hometown: "Us"}, {studentid:"102", Name: "CCC", Hometown: "England"}]
On the server side, you can easily convert a JSON string to a JSON object using the parse method of Jobject or Jarray, and then extract the data by object. The following is the service-side code.
protected voidPage_Load (Objectsender, EventArgs e) { stringInputjsonstring =@"[{studentid: ' + ', Name: ' AAA ', Hometown: ' China '}, {studentid: ' 101 ', Name: ' BBB ', Hometown: ' Us '}, {studentid: ' 102 ', Name: ' CCC ', Hometown: ' England '}]"; Jarray Jsonobj=Jarray.parse (inputjsonstring); stringMessage =@"<table border= ' 1 ' > <tr><td width= ' ">studentid</td><td width= ' >n ' AME</TD><TD width= ' >Hometown</td></tr>"; stringTPL ="<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"; foreach(Jobject Jobjectinchjsonobj) {Message+ = String.Format (TPL, jobject["StudentID"], jobject["Name"],jobject["Hometown"]); } Message+="</table>"; Lbmsg.innerhtml=message; }
Output Result:
of course, the service side can use the JsonConvert Deserializeobject method in addition to using LINQ to JSON for converting JSON strings. The following code implements the same functionality as above.
list<student> studentlist = jsonconvert.deserializeobject<list<student>> (inputJsonString); // Note that this must be a list<student> type, because the client commits an array JSON foreach inch studentlist) { + = String.Format (TPL, student. StudentID, student. Name,student. Hometown); }
Summarize
On the client side, the read-write JSON object can use the "." operator or "[" Key "]", the JSON string is converted to a JSON object using the eval () function.
On the server side, the JSON string converted by the. NET object takes precedence using the SerializeObject method of the JsonConvert object, customizing the output JSON string using LINQ to JSON. Converting from a JSON string to a. NET object takes precedence over the Deserializeobject method of the JsonConvert object, and then also uses LINQ to JSON.