. Net in-depth practical series-JSON serialization, json serialization

Source: Internet
Author: User
Tags net serialization serialization definition

. Net in-depth practical series-JSON serialization, json serialization
Collation

Currently, there are two main methods to serialize JSON strings: JavaScriptSerializer and Json.net (Nuget ID: Newtonsoft. Json ). JavaScriptSerializer is a method officially provided by Microsoft. Therefore, if you are using asp.net mvc, in the Action, if the returned statement is "return Json (xxx);", in fact, you are using the JavaScriptSerializer method. Now more people choose Json.net because it provides users with a clearer user experience? This article mainly takes you into their world.

JavaScriptSerializer and Json.net serialization

Let's first define a simple test class -- Person:

  public class Person    {        public string Name;        public int Age;        public Guid TokenId;        public DateTime RegTime;        public Person Child;        public Person Friend;    }

Class Members are only used to differentiate different variable types. We serialize criptserializer and Json.net respectively:

Var person = new Person {Age = 28, Name = "Li Yubao <yubaolee:>", // intentionally Add the special character RegTime = DateTime. now, TokenId = Guid. newGuid (), Child = new Person {Age = 1, Name = "baby", RegTime = DateTime. now, TokenId = Guid. newGuid () }}; // note that the specified Friend is not assigned a value. The default value is empty. JavaScriptSerializer serializer = new JavaScriptSerializer (); var jsstr = serializer. serialize (person); // use JavaScriptSerializer to Serialize string newtonstr = JsonConvert. serializeObject (person); // use Json.net for serialization

JavaScriptSerializer serialization is an object, and then calls its member function Serialize for serialization;

Json.net uses the provided static member JsonConvert. SerializeObject for serialization;

Both of them are simple to use, and Json.net is easy to call! Let's take a look at the console output results:

Jsstr = Regex. replace (jsstr, @ "\/Date \ (\ d +) \/", match => {DateTime dt = new DateTime (1970, 1, 1); dt = dt. addMilliseconds (long. parse (match. groups [1]. value); dt = dt. toLocalTime (); return dt. toString ("yyyy-MM-dd HH: mm: ss ");});

Effect after processing:

String newtonstr = JsonConvert. SerializeObject (p, Formatting. Indented, new IsoDateTimeConverter () {DateTimeFormat = "yyyy-MM-dd HH: mm: ss "});

2. JavaScriptSerializer serializer will encode special characters (such as <>), for example, the above \ u003c \ u003e. When many people see this, the first thought is too boring, the next step is how Baidu converts this into a normal "<> ". In fact, you don't need to do anything. This is a standard JS encoding method, and the front-end will handle this problem on its own. For example:

<Script type = "text/javascript"> var str = 'yubaolee <yubaolee> 'var str2 = 'yubaolee \ u003cyubaolee \ u003e '; alert (str = str2 ); // The result is true. </script>

Appendix: If you really don't understand what \ u003c is, please go to character encoding.

 

From the above two points, we can see that the JSON string serialized by JavaScriptSerializer is easy to cause some confusion, while Json.net does not deal with the above two situations. So many people are using Json.net, but from the Html standard point of view, the result serialized by JavaScriptSerializer is more in line with the Html requirements. For operational habits, we recommend using Json.net.

Deserialization

We use two methods to deserialize the two strings successfully serialized above:

// Deserialize the string generated by JavaScriptSerializer // use the JavaScriptSerializer method var jsperson = serializer. deserialize <Person> (jsstr); // use the Json.net method var newtonperson = JsonConvert. deserializeObject <Person> (jsstr); // deserializes the string generated by Json.net. var jsperson2 = serializer. deserialize <Person> (newtonstr); var newtonperson2 = JsonConvert. deserializeObject <Person> (newtonstr );

After running, we can find that all four deserialization codes can run normally, instead of deserializing the criptserializer, json.net deserialization strings can only be deserialized using Json.net.

The deserialization string is generated by the program. It is not surprising that normal deserialization can be performed. But the string we usually want to deserialize is the string that the customer submits to the server. They are generally incomplete, or some types may not match. For example:

String noChildStr = "{\" Name \ ": \" Li Yubao <yubaolee:> \ "," + "\" Age \ ": 28, "+" \ "RegTime \": \ "00:10:48 \", "+" \ "Friend \": null} "; var jsperson = new JavaScriptSerializer (). deserialize <Person> (noChildStr); var newtonperson = JsonConvert. deserializeObject <Person> (noChildStr );

Note that this string contains no TokenId, no Child, and the Friend is null. Take a look at the results:

String noChildStr = "{\" Name \ ": \" Li Yubao <yubaolee:> \ "," + "\" Age \ ": 28, "+" \ "RegTime \": \ "00:10:48 \", "+" \ "Friend \": null, "+" \ "TokenId \": null }"; // note that this TokenId is empty

When running, the program will directly report an error.

Public class PersonJsConverter: JavaScriptConverter {public override object Deserialize (IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer) {Person person Person = new Person (); object value = null; if (dictionary. tryGetValue ("TokenId", out value) & value! = Null) person. tokenId = (Guid) value; // other fields... return person;} public override IDictionary <string, object> Serialize (object obj, JavaScriptSerializer serializer) {Dictionary <string, object> dic = new Dictionary <string, object> (); var node = obj as Person; if (node = null) return null; if (! String. isNullOrEmpty (node. name) dic. add ("Name", node. name); // other fields... return dic;} public override IEnumerable <Type> SupportedTypes {get {return new Type [] {typeof (Person )};}}}

Then, before deserialization, we register the conversion to the object, and then execute it, and the program will be normal:

JavaScriptSerializer serializer = new JavaScriptSerializer();serializer.RegisterConverters(new JavaScriptConverter[] { new PersonJsConverter(),  });var deserialize = serializer.Deserialize<Person>(noChildStr);

2. When using Json.net, it adopts a more elegant way to handle this problem-JsonConverter, which can independently process a specified class member variable. In this way, you do not need to process all the members of the entire class like the JavaScriptConverter above. The Code is as follows:

Public class GuidConverter: JsonConverter {public override bool CanConvert (Type objectType) {return objectType. isAssignableFrom (typeof (Guid);} public override object ReadJson (JsonReader, Type objectType, object existingValue, JsonSerializer serializer) {try {return serializer. deserialize <Guid> (reader);} catch {// If the passed value causes an exception, an initial value return Guid is assigned. empty ;}} public override void WriteJson (JsonWriter, object value, JsonSerializer serializer) {serializer. serialize (writer, value );}}

It is worth noting that JsonConverter is an Attribute, so you must add a feature to the class member:

  public class Person    {        public string Name;        public int Age;        [JsonConverter(typeof(GuidConverter))]        public Guid TokenId { get; set; }        public DateTime RegTime;        public Person Child;        public Person Friend;    }

Then, when you run the program, the TokenId will be assigned an initial value. It seems that Json.net is better in deserialization.

Performance

Here are two performance comparisons on the Internet:

In summary, we try to use Json.net for Object serialization without considering the system's requirements for third-party controls.

 

Other common serialization Methods

After half a day, let's review the serialization definition:

Serialization: Converts an object into a word throttling process, so that the object can be easily stored in a disk file or database.

Deserialization: The deserialization inverse process refers to the process of converting byte streams back to the original object.

For other serialization methods in different formats, see:

Serialization and deserialization, and Json deserialization

About serialization and deserialization in. Net

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.