JSON serialization and deserialization of DotNet and dotnetjson serialization
JSON (JavaScript Object Notation) JavaScript Object Notation, which is a text-based lightweight data exchange format independent of languages. In the current communication, the JSON data format is mostly used. JSON has two types of representation structure, object and array. JSON data is written in the format of name/value pair.
In vs solution, the structure of the project was previously organized in the form of an xml tree. In the new. net core, the project solution uses json as the project structure description.
In front and back-end data interaction of. net, the serialized object is json, the front-end ajax receives the transmitted data, deserializes the object, and renders the data on the page. Json-related content is not described in detail. Classes serialized in. net mainly use the DataContractJsonSerializer class.
Now we provide a general method for json serialization and deserialization.
1. json serialization:
/// <Summary> /// serialize the object to JSON /// </summary> /// <typeparam name = "T"> serialization type </typeparam>/ // <param name = "t"> serialized object </param> // <returns> serialized JSON </returns> public static string JsonSerializer <T> (T t) {if (t = null) throw new ArgumentNullException ("t"); string jsonString; try {var ser = new DataContractJsonSerializer (typeof (T )); varMS = new MemoryStream (); ser. writeObject (MS, t); jsonString = Encoding. UTF8.GetString (ms. toArray (); ms. close (); // Replace the Json Date string const string p = @ "\/Date \ (\ d +) \ + \ d + \)\\/"; var matchEvaluator = new MatchEvaluator (ConvertJsonDateToDateString); var reg = new System. text. regularExpressions. regex (p); jsonString = reg. replace (jsonString, matchEvaluator);} catch (Exception er) {throw new Exception (er. message);} return jsonString ;}
2. deserialization of json:
/// <Summary> /// deserialize JSON into an object // </summary> public static T JsonDeserialize <T> (string jsonString) {if (string. isNullOrEmpty (jsonString) throw new Exception (jsonString); // convert the string in the format of "yyyy-MM-dd HH: mm: ss" to "\/Date (1294499956278 + 0800) \/"format const string p = @" \ d {4}-\ d {2}-\ d {2} \ s \ d {2 }: \ d {2 }:\ d {2} "; try {var matchEvaluator = new MatchEvaluator (ConvertDateStringToJsonDate); var reg = new System. text. regularExpressions. regex (p); jsonString = reg. replace (maid, matchEvaluator); var ser = new DataContractJsonSerializer (typeof (T); var MS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString); var obj = (T) ser. readObject (MS); return obj;} catch (Exception ex) {throw new Exception (ex. message, ex );}}
The preceding is a simple json serialization and deserialization method.