Newtonsoft.json, an open source Json serialization and deserialization class library in. NET, obtained through NuGet. (View original)
The following is a simple encapsulation of JSON serialization and deserialization:
/// <summary> ///JSON helper Class/// </summary> Public classJsonhelper {/// <summary> ///serializing objects to JSON format/// </summary> /// <param name= "O" >Object</param> /// <returns>JSON string</returns> Public Static stringSerializeObject (Objecto) {stringJSON =Jsonconvert.serializeobject (o); returnJSON; } /// <summary> ///parsing JSON strings generating object entities/// </summary> /// <typeparam name= "T" >Object Type</typeparam> /// <param name= "JSON" >JSON string (eg.{" ID ":" "" "," "Name": "Pebblessintosthe"})</param> /// <returns>Object Entity</returns> Public StaticT deserializejsontoobject<t> (stringJsonwhereT:class{Jsonserializer Serializer=NewJsonserializer (); StringReader SR=NewStringReader (JSON); Objecto = serializer. Deserialize (NewJsonTextReader (SR),typeof(T)); T T= O asT; returnT; } /// <summary> ///parse JSON array to generate object entity collection/// </summary> /// <typeparam name= "T" >Object Type</typeparam> /// <param name= "JSON" >JSON array string (eg.[ {"ID": "Pebblessintosthe", "Name": "{"}])</param> /// <returns>Object Entity Collection</returns> Public StaticList<t> deserializejsontolist<t> (stringJsonwhereT:class{Jsonserializer Serializer=NewJsonserializer (); StringReader SR=NewStringReader (JSON); Objecto = serializer. Deserialize (NewJsonTextReader (SR),typeof(list<t>)); List<T> list = O asList<t>; returnlist; } /// <summary> ///deserializes the JSON to the given anonymous object. /// </summary> /// <typeparam name= "T" >Anonymous Object Types</typeparam> /// <param name= "JSON" >JSON string</param> /// <param name= "Anonymoustypeobject" >Anonymous Objects</param> /// <returns>Anonymous Objects</returns> Public StaticT deserializeanonymoustype<t> (stringjson, T anonymoustypeobject) {T T=Jsonconvert.deserializeanonymoustype (JSON, anonymoustypeobject); returnT; } }
To further understand Newtonsoft, some examples of tests have been written:
/// <summary> ///JSON test/// </summary> Public classJsontest:irun { Public voidRun () {Student sdudent=NewStudent (); Sdudent.id=1; Sdudent. Name="Chen Chen"; Sdudent. Nickname="pebblessintosthe"; Sdudent. Class=NewClass () {Name ="CS0216", ID =0216 }; //entity serialization and deserialization stringJson1 =Jsonhelper.serializeobject (sdudent); //Json1: {"id": 1, "name": "Chen Chen", "nickname": "Pebblessintosthe", "Class": {"id": 216, "name": "CS0216"}}Student sdudent1 = jsonhelper.deserializejsontoobject<student>(Json1); //serialization and deserialization of entity collectionsList<student> sdudentlist =NewList<student>() {sdudent, sdudent1}; stringJson2 =Jsonhelper.serializeobject (sdudentlist); //JSON: [{"id": 1, "name": "Chen Chen", "nickname": "Pebblessintosthe", "Class": {"id": 216, "name": "CS0216"}},{"id": 1, "name": "Chen Chen", " Nickname ":" Pebblessintosthe "," Class ": {" ID ": 216," Name ":" CS0216 "}}]list<student> SdudentList2 = jsonhelper.deserializejsontolist<student>(Json2); //DataTable serialization and deserializationDataTable dt =NewDataTable (); Dt. TableName="Student"; Dt. Columns.Add ("ID",typeof(int)); Dt. Columns.Add ("Name"); Dt. Columns.Add ("Nickname"); DataRow Dr=dt. NewRow (); dr["ID"] = the; dr["Name"] ="War III"; dr["Nickname"] ="Small Three"; Dt. Rows.Add (DR); stringJson3 =jsonhelper.serializeobject (DT); //Json3: [{"ID": "nickname", "Name": "Battle Three", "Small Three"}]DataTable SDUDENTDT3 = jsonhelper.deserializejsontoobject<datatable>(Json3); List<Student> SdudentList3 = jsonhelper.deserializejsontolist<student>(Json3); //validating objects and ArraysStudent sdudent4 = jsonhelper.deserializejsontoobject<student> ("{\ "id\": \ "112\", \ "name\": \ "pebblessintosthe \"}"); List<Student> SdudentList4 = jsonhelper.deserializejsontolist<student> ("[{\ "id\": \ "112\", \ "name\": \ "pebblessintosthe \"}]"); //Anonymous Object parsing varTempentity =New{ID =0, Name =string. Empty}; stringJson5 =Jsonhelper.serializeobject (tempentity); //json5: {"ID": 0, "Name": ""}Tempentity = Jsonhelper.deserializeanonymoustype ("{\ "id\": \ "112\", \ "name\": \ "pebblessintosthe \"}", tempentity); varTempstudent =NewStudent (); Tempstudent= Jsonhelper.deserializeanonymoustype ("{\ "id\": \ "112\", \ "name\": \ "pebblessintosthe \"}", tempstudent); Console.read (); } } /// <summary> ///Student Information Entity/// </summary> Public classStudent { Public intID {Get;Set; } Public stringName {Get;Set; } Public stringNickname {Get;Set; } PublicClass Class {Get;Set; } } /// <summary> ///Student class Entities/// </summary> Public classClass { Public intID {Get;Set; } Public stringName {Get;Set; } }
There are two points to note when using the JSON helper class:
1. It is usually possible to serialize the SerializeObject () and deserialize Deserializejsontoobject () using the calling entity () two methods. However, in some cases when we parse the JSON string, there may be no corresponding entity type (or do not want to add the corresponding entity Class), this time can use the Anonymous object parsing method Deserializeanonymoustype (), convenient and quick, the corresponding code is as follows:
Anonymous object Resolution var tempentity = new {ID = 0, Name = string. Empty}; String json5 = Jsonhelper.serializeobject (tempentity); Json5: {"ID": 0, "Name": ""} tempentity = Jsonhelper.deserializeanonymoustype ("{\" id\ ": \" 112\ ", \" name\ ": \" pebblessintosthe \ "}", tempentity); Console.WriteLine (Tempentity.id + ":" + tempentity.name);
2. Two structure arrays of JSON and object parsing are slightly different. JSON objects are generally converted to entities, and JSON arrays are generally converted into entity collections. The code is as follows:
Validation object and array Student sdudent4 = jsonhelper.deserializejsontoobject<student> ("{\" id\ ": \" 112\ ", \" name\ ": \" Pebblessintosthe \ "}"); list<student> sdudentList4 = jsonhelper.deserializejsontolist<student> ("[{\" id\ ": \" 112\ ", \" name\ ": \" Pebblessintosthe \ "}]");
Explain the meanings of JSON objects and arrays in a nutshell:
The object is terminated with "{" (opening parenthesis), "}" (closing parenthesis). Each "name" is followed by a ":" (colon); "' Name/value ' pairs" are separated by "," (comma). The name is enclosed in quotation marks, and if the value is a string, it must be in parentheses, and the numeric type is not required. For example: {"ID": "" "," "Name": "Pebblessintosthe"}.
An array is an ordered collection of values (value). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values. For example: [{"id": "pebblessintosthe", "name": "},{", "id": "113", "name": "Chen Chen"}].
Newtonsoft.json (json.net) study notes (GO)