Reprinted -- Json conversion, reprinted -- json

Source: Internet
Author: User

Reprinted -- Json conversion, reprinted -- json
 

The full name of JSON is "JavaScript Object Notation", which means JavaScript Object Notation. It is a text-based lightweight data exchange format independent of languages. XML is also a data exchange format. Why is XML not used? Although XML can be used as a cross-platform data exchange format, it is inconvenient to process XML in JavaScript (abbreviated as JavaScript). XML tags are more than data, which increases the traffic generated by the exchange, JSON does not have any tag attached and can be processed as an object in JS. Therefore, we prefer JSON to exchange data. This article mainly describes JSON in the following aspects.

1. Two JSON Structures
2. Understand JSON strings
3. How to Use JSON in JS
4. How to Use JSON in. NET
5. Summary

Two JSON Structures

JSON has two types of representation structures: objects and arrays.
The object structure starts with braces ({) and ends with braces. The middle part consists of 0 or multiple key (keyword)/value (value) pairs separated by ",". The keywords and values are separated, the syntax structure is like code.

{    key1:value1,    key2:value2,    ...}

The keywords are strings, while the values can be strings, values, true, false, null, objects, or arrays.

The array structure ends. There are 0 or multiple value lists separated by "," in the middle. The syntax structure is like code.

12345678910 [    {        key1:value1,        key2:value2    },    {         key3:value3,         key4:value4      }]

 

Understanding JSON strings

I have been confused about the differences between common strings, json strings, and json objects. After some research, I finally figured it out. For example, in js.

String: This is a good explanation. It refers to the character that uses "" Double quotation marks or ''single quotation marks. For example, var comStr = 'this is string ';
Json string: A js string that meets the json format requirements. For example: var jsonStr = "{StudentID: '000000', Name: 'tmac', Hometown: 'usa '}";
Json object: A js object that meets the json format requirements. Example: var jsonObj = {StudentID: "100", Name: "tmac", Hometown: "usa "};

How to Use JSON in JS

JSON is a subset of JS, so you can easily read and write JSON in JS. Two methods are available for reading and writing JSON, namely using the "." operator and "[key]" method.
First, we define a JSON object. The Code is as follows.

Var obj = {"1": "value1", "2": "value2", count: 3, person: [// JSON object of the array structure, which can be nested with {id: 1, name: "Zhang Qian" },{ id: 2, name: "Zhang Shuai"}], object: {// JSON object id: 1, msg: "object "}};

1. read data from JSON

Function ReadJSON () {alert (obj.1); // a syntax error is reported. You can use alert (obj ["1"]). It indicates that the number is better not to be a keyword alert (obj.2 ); // same as 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 JSON, the Code is as follows:

Function Add () {// Add a record to the JSON object obj. sex = "male" // or obj ["sex"] = "male "}

JSON object after adding data

3. modify data in JSON

Now we want to modify the count value in JSON. The Code is as follows:

Function Update () {obj. count = 10; // or obj ["count"] = 10}

The modified JSON.

4. delete data in JSON

Now we can delete the count data from JSON. The Code is as follows:

function Delete() {            delete obj.count;        }

Deleted JSON

You can see that count has been deleted from the JSON object.

5. Traverse JSON objects

You can use... In... Loop to traverse the data in the JSON object. For example, 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 result is:

The program output result is:

How to Use JSON in. NET

When it comes to using JSON in. net, we have to mention JSON. NET. It is a very famous tool for processing JSON in. net. The most commonly used are the following two features.

1. Convert. net objects to JSON strings through serialization

During web development, we often need to convert the data (generally a collection, list, or array) queried from the database into JSON format strings and send them back to the client, this requires sorting. Here we use the SerializeObject method of the JsonConvert object. The syntax format is JsonConvert. SerializeObject (object). The "object" in the Code is the. net object to be serialized, And the json string is returned after serialization.

For example, we now have a student table named TStudent, which contains fields and existing data.

We can see a total of five pieces of data from the table. Now we need to extract the data from the database, and then serialize them as JSON strings using the json. NET JsonConvert object and display them on the page. C # The Code is as follows:

1 protected void Page_Load (object sender, EventArgs e) 2 {3 using (L2SDBDataContext db = new L2SDBDataContext ()) 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. classID, 14 Weight = s. weight, 15 Height = s. height, 16 Desc = s. desc17}; 18 foreach (var item in query) // cyclically traverse the array and convert the object 19 {20 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); 22} 23 lbMsg. innerText = JsonConvert. serializeObject (studentList); 24} 25}

Output result

We can see that all five records in the database are retrieved and converted to a json string.

2. Use LINQ to JSON to customize JSON data

SerializeObject using the JsonConvert object simply converts a list or set to a json string. However, sometimes our front-end framework, such as ExtJs, has certain requirements on the data format returned by the server. For example, the following data format requires JSON. NET. The function of LINQ to JSON is to customize JSON data according to the required format.

For example, the json format that is often used in paging is code:

{"Total": 5, // total number of records "rows": [// data list in json format]}

Before using LINQ to JSON, you must reference the dll of Newtonsoft. Json and the namespace of using Newtonsoft. Json. Linq. LINQ to JSON mainly uses JObject, JArray, JProperty, and JValue objects. JObject is used to generate a JSON object. In short, it generates "{}", JArray is used to generate a JSON number group, that is, "[]". JProperty is used to generate a JSON data value in the format of key/value, while JValue directly generates a JSON value. In the following example, data in the preceding paging format is returned using LINQ to JSON. The Code is as follows:

1 protected void Page_Load (object sender, EventArgs e) 2 {3 using (L2SDBDataContext db = new L2SDBDataContext ()) 4 {5 // retrieve data from the database and put it in the list List. 6 lists <Student> studentList = new List <Student> (); 7 var query = from s in db. TStudents 8 select new 9 {10 StudentID = s. studentID, 11 Name = s. name, 12 Hometown = s. hometown, 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 created list, use LINQ to JSON to create JSON data in the expected format 27 lbMsg. innerText = new JObject (28 new JProperty ("total", studentList. count), 29 new JProperty ("rows", 30 new JArray (31 // you can directly generate a JSON data object in the select statement using LINQ to JSON, no other conversion procedure 32 from p in studentList33 select new JObject (34 new JProperty ("studentID", p. studentID), 35 new JProperty ("name", p. name), 36 new JProperty ("homeTown", p. hometown) 37) 38) 39) 40 ). toString (); 41} 42}

Output result:

 

3. Process JSON data submitted by the client

The data submitted by the client is generally a json string and can be better operated (in an object-oriented manner). Therefore, we generally want to convert the json string to a json object. For example, the client submits the following array format json string.

[    {StudentID:"100",Name:"aaa",Hometown:"china"},    {StudentID:"101",Name:"bbb",Hometown:"us"},    {StudentID:"102",Name:"ccc",Hometown:"england"}]

On the server side, you can use the Parse method of JObject or JArray to easily convert a json string to a json object, and then extract data through the object. The following is the server code.

 1 protected void Page_Load(object sender, EventArgs e) 2         { 3             string inputJsonString = @" 4                 [ 5                     {StudentID:'100',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);10             string message = @"<table border='1'>11                     <tr><td width='80'>StudentID</td><td width='100'>Name</td><td width='100'>Hometown</td></tr>";12             string tpl = "<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>";13             foreach (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 server can use the DeserializeObject method of JsonConvert in addition to using LINQ to JSON to convert json strings.The following code implements the same functions.

List <Student> studentList = JsonConvert. deserializeObject <List <Student> (inputJsonString); // note that the value must be of the List <Student> type, because the client submits an array of json foreach (Student student in studentList) {message + = String. format (tpl, student. studentID, student. name, student. hometown );}
Summary

On the client side, you can use the "." operator or "[" key "]" to read and write json objects. to convert a json string to a json object, use the eval () function.
On the service end, the SerializeObject method of the JsonConvert object is preferred for converting json strings from A. net object, and the custom output json string is using the LINQ to JSON method. The DeserializeObject method of the JsonConvert object is preferred to be converted from a json string to A. net object. You can also use the LINQ to JSON method.

You can call the method as needed. However, you can also use the dll file Newtonsoft. Json.

1 JObject json = (JObject) JsonConvert. deserializeObject (str); 2 JArray array = (JArray) json ["article"]; 3 foreach (var jObject in array) 4 {5 // assign a value to attribute 6}
Reprinted Source: http://www.cnblogs.com/QLJ1314/p/3862583.html http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html

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.