Reprint--json Conversion

Source: Internet
Author: User
Tags string back

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.

12345678910 [    {        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",            count:3, person            : [//array structure JSON object, can be nested using                        {                            id:1,                            Name: "Zhang Qian"                        },                        {                            id:2,                            name: "Zhang Shuai"                        }                   ], object            : {//Object structure JSON object                id:1,                msg: " Object in the object "                }        };

1, reading data from JSON

function Readjson () {            alert (obj.1);//Report syntax error, can use alert (obj["1"]), it is best not to do the keyword            alert (obj.2)            ; alert (obj.person[0].name); or alert (obj.person[0]["name"])            alert (obj.object.msg);//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            obj.sex= "male"//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 () {            obj.count = 10;//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. c in obj) {                Console.log (c + ":", Obj[c]);}        }

The program output results are:

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

 1 protected void Page_Load (object sender, EventArgs e) 2 {3 using (L2sdbdatacontext db = new L2sdbda                 Tacontext ()) 4 {5 list<student> studentlist = new list<student> (); 6 var query = from S in db.                                 Tstudents 7 Select New {8 Studentid=s.studentid, 9                                 name=s.name,10 hometown=s.hometown,11 gender=s.gender,12 brithday=s.birthday,13 Classid=s.cla                                 ssid,14 weight=s.weight,15 height=s.height,16 Desc=s.desc17};18 foreach (var item in query)//Loop through array, go Change Object {Student Student = new Student {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};21 Studentlist.add (student);}23 Lbmsg.innertext = JsonConvert . SerializeObject (studentlist); 24}25}

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": 5,//number    of 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:

 1 protected void Page_Load (object sender, EventArgs e) 2 {3 using (L2sdbdatacontext db = new L2sdbda Tacontext ()) 4 {5//Fetch data from the database and put it in list 6 list<student> studentlist = n EW list<student> (); 7 var query = from S in db. Tstudents 8 Select New 9 {stude Ntid = s.studentid,11 Name = s.name,12 Hometown = S.hometo                                 wn,13 Gender = s.gender,14 Brithday = s.birthday,15                                 ClassID = s.classid,16 Weight = s.weight,17                 Height = s.height,18 Desc = s.desc19};20                    foreach (var item in query) 21 {22 Student Student = new Student {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};23 Studentlist.add (student); 24}25 26//Based on the list created, use the LINQ to JSON Create the JSON data for the desired format lbmsg.innertext = new Jobject ("Total", studentlist .                                         Count), New Jproperty ("Rows", New Jarray (31  Using LINQ to JSON, you can generate JSON data objects directly in a SELECT statement without the need for another conversion process from the P in                                                 StudentList33 Select New Jobject (34 New Jproperty ("StudentID", P.studentid), New Jproperty ("name", P.name),                                36                 New Jproperty ("Hometown", P.hometown) 37) 38 ) (39) 40). ToString (); 41}42}

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.

 1 protected void Page_Load (object sender, EventArgs e) 2 {3 String inputjsonstring = @ "4 [5 {studentid: ' + ', Name: ' AAA ', Hometown: ' China '}, 6 {studentid: ' 101 ', Name: ' BBB ', Hometown: ' Us '}, 7 {studentid: ' 102 ', Name: ' CCC ', Hometown: ' England '} 8] ";                     9 Jarray jsonobj = Jarray.parse (inputjsonstring), ten string message = @ "<table border= ' 1 ' >11 &LT;TR&GT;&LT;TD width= ' >studentid</td><td width= ' >name</td><td width= ' ">Hometown</td></tr>"; "String tpl =" <tr><td>{0}</td><td>{1}</t                 D><td>{2}</td></tr> "(Jobject jobject in Jsonobj) 14 {15             Message + = String.Format (TPL, jobject["StudentID"], jobject["Name"],jobject["Hometown"]); 16}17 Message + = "</table>"; 18 lbmsg.innerhtml = message;19} 

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 is submitting an array of JSON            foreach (Student Student in studentlist)            {                message + = 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.

Call the method according to the desired line. However, you can also use Newtonsoft.json this DLL file, if you are converting an array, use the

1 Jobject json = (jobject) jsonconvert.deserializeobject (str), 2         jarray array = (Jarray) json["article"];3  foreach (var jobject in array) 4         {5           //assignment Property 6}
Reprint Source: http://www.cnblogs.com/QLJ1314/p/3862583.html http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html

Reprint--json Conversion

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.