C #,
Recently, some json problems were used during development, that is, some of the returned json data is processed, but the json data is not well mastered, I have wasted a lot of time searching for json-related conversions. All I know is to serialize and deserialize json, but it is too troublesome, so we are looking for some simpler and more convenient methods. This may be useful, so it can be used after it is put here.
Source: http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html
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
Function Update () {obj. count = 10; // or obj ["count"] = 10}
The modified JSON.
Function Delete () {delete obj. count ;}
Deleted JSON
Function Traversal () {for (var c in obj) {console. log (c + ":", obj [c]) ;}}
The program output result is:
The program output result is:
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}View Code
Output result
{"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}View Code
Output result:
[{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: '000000', Name: 'aaa', Hometown: 'China'}, 6 {StudentID: '000000', Name: 'bbb ', Hometown: 'us'}, 7 {StudentID: '000000', 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 = '000000'> Name </td> <td width = '000000'> 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}View Code
Output result:
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 server side, the SerializeObject method of the JsonConvert object is preferred for converting json strings from A. net object, and the custom output json string is made using LINQ to JSON. 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}View Code