Newtonsoft. Json (Json. Net) study notes, newtonsoft. json

Source: Internet
Author: User

Newtonsoft. Json (Json. Net) study notes, newtonsoft. json

Newtonsoft. Json, a class library (http://json.codeplex.com/) for open-source Json serialization and deserialization in. NET /).

The following is a simple encapsulation of Json serialization and deserialization:

/// <Summary> /// Json help class /// </summary> public class JsonHelper {// <summary> // serialize the object to JSON format // /</summary> // <param name = "o"> object </param> // <returns> json string </returns> public static string SerializeObject (object o) {string json = JsonConvert. serializeObject (o); return json ;} /// <summary> /// parse the JSON string to generate the object entity /// </summary> /// <typeparam name = "T"> Object Type </typeparam>/ // <param name = "json"> json string (eg. {"ID": "112", "Name": "Shi Er "}) </param> // <returns> Object entity </returns> public static T DeserializeJsonToObject <T> (string json) where T: class {JsonSerializer serializer = new JsonSerializer (); stringReader sr = new StringReader (json); object o = serializer. deserialize (new JsonTextReader (sr), typeof (T); T t = o as T; return t ;} /// <summary> // parse the JSON array to generate an object set /// </summary> /// <typeparam name = "T"> Object Type </typeparam> /// <param name = "json"> json array string (eg. [{"ID": "112", "Name": "Shi Er"}]) </param> // <returns> Object entity set </returns> public static List <T> DeserializeJsonToList <T> (string json) where T: class {JsonSerializer serializer = new JsonSerializer (); StringReader sr = new StringReader (json); object o = serializer. deserialize (new JsonTextReader (sr), typeof (List <T>); List <T> list = o as List <T>; return list ;} /// <summary> /// deserialize JSON to the specified anonymous object. /// </summary> /// <typeparam name = "T"> anonymous object type </typeparam> /// <param name = "json"> json string </ param> /// <param name = "anonymousTypeObject"> anonymous object </param> // <returns> anonymous object </returns> public static T DeserializeAnonymousType <T> (string json, T anonymousTypeObject) {T t = JsonConvert. deserializeAnonymousType (json, anonymousTypeObject); return t ;}}View Code

To further understand Newtonsoft, I wrote some test examples:

/// <Summary> /// Json test /// </summary> public class JsonTest: IRun {public void Run () {Student sdudent = new Student (); sdudent. ID = 1; sdudent. name = "Chen"; sdudent. nickName = "Shi Er"; sdudent. class = new Class () {Name = "CS0216", ID = 0216}; // Object serialization and deserialization string json1 = JsonHelper. serializeObject (sdudent); // json1: {"ID": 1, "Name": "Chen", "NickName": "Shi Er", "Class ": {"ID": 216, "Name": "CS0216"} Student sdudent1 = JsonHelper. deserializeJsonToObject <Student> (json1); // object set serialization and deserialization List <Student> sdudentList = new List <Student> () {sdudent, sdudent1}; string json2 = JsonHelper. serializeObject (sdudentList); // json: [{"ID": 1, "Name": "Chen", "NickName": "Shi Er", "Class ": {"ID": 216, "Name": "CS0216" }}, {"ID": 1, "Name": "Chen", "NickName ": "Shi Er", "Class": {"ID": 216, "Name": "CS0216" }}] List <Student> sdudentList2 = JsonHelper. deserializeJsonToList <Student> (json2); // able serialization and deserialization DataTable dt = new DataTable (); dt. tableName = "Student"; dt. columns. add ("ID", typeof (int); dt. columns. add ("Name"); dt. columns. add ("NickName"); DataRow dr = dt. newRow (); dr ["ID"] = 112; dr ["Name"] = "battle 3"; dr ["NickName"] = "John"; dt. rows. add (dr); string json3 = JsonHelper. serializeObject (dt); // json3: [{"ID": 112, "Name": "3", "NickName":" 3"}] DataTable sdudentDt3 = JsonHelper. deserializeJsonToObject <DataTable> (json3); List <Student> sdudentList3 = JsonHelper. deserializeJsonToList <Student> (json3); // verify the object and the array Student sdudent4 = JsonHelper. deserializeJsonToObject <Student> ("{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \"}"); list <Student> sdudentList4 = JsonHelper. deserializeJsonToList <Student> ("[{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \ "}]"); // resolve the var tempEntity = new {ID = 0, Name = string. empty}; string json5 = JsonHelper. serializeObject (tempEntity); // json5: {"ID": 0, "Name": ""} tempEntity = JsonHelper. deserializeAnonymousType ("{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \ "}", tempEntity ); var tempStudent = new Student (); tempStudent = JsonHelper. deserializeAnonymousType ("{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \ "}", tempStudent); Console. read () ;}/// <summary> // Student Information Entity // </summary> public class Student {public int ID {get; set ;} public string Name {get; set;} public string NickName {get; set;} public Class {get; set ;}} /// <summary> /// student class entity /// </summary> public Class {public int ID {get; set;} public string Name {get; set ;}}View Code

When using the Json help class, pay attention to the following two points:

1. You can call the object serialization SerializeObject () and deserialization DeserializeJsonToObject () methods. However, in some cases, when parsing a json string, there may be no corresponding entity type (or we do not want to add the corresponding entity class). In this case, we can use the anonymous Object Parsing Method DeserializeAnonymousType (), which is convenient and fast, the Code is as follows:

// Resolve the var tempEntity = new {ID = 0, Name = string. empty}; string json5 = JsonHelper. serializeObject (tempEntity); // json5: {"ID": 0, "Name": ""} tempEntity = JsonHelper. deserializeAnonymousType ("{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \ "}", tempEntity); Console. writeLine (tempEntity. ID + ":" + tempEntity. name );

2. Json arrays and objects are slightly different during parsing. Json objects are generally converted to objects, while Json arrays are generally converted to object sets. The Code is as follows:

// Verify the object and the array Student sdudent4 = JsonHelper. deserializeJsonToObject <Student> ("{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \"}"); list <Student> sdudentList4 = JsonHelper. deserializeJsonToList <Student> ("[{\" ID \ ": \" 112 \ ", \" Name \ ": \" Shi Er \ "}]");

Briefly explain the meaning of Json objects and arrays:

The object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs. The name is enclosed in quotation marks. If the value is a string, it must be enclosed in parentheses, but not numeric. For example: {"ID": "112", "Name": "Shi Er "}.

An array is an ordered set of values. An array starts with "[" (left square brackets) and ends with "]" (right square brackets. Values are separated by commas. For example: [{"ID": "112", "Name": "Shi Er" },{ "ID": "113", "Name ": "Chen"}].

 

Related Article

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.