JSON serialization that's a little bit of a thing

Source: Internet
Author: User
Tags net serialization object serialization

JSON serialization that point of order

There are two main ways to serialize Json strings in the current mainstream: JavaScriptSerializer and Json.NET (NuGet identity: Newtonsoft.json). JavaScriptSerializer is a method that Microsoft officially provides, so if you are using ASP. NET MVC, in action if you return a statement that says "return Json (XXX);", In fact, you use the JavaScriptSerializer way. Now more people choose Json.NET, because it provides users with a clearer use of the experience, where is the clarity? This article is mainly to take you into their world.

JavaScriptSerializer and Json.NET serialization

Let's first define a simple class--person for testing:

  1. Public class person
  2. {
  3. public string Name;
  4. public int age;
  5. Public Guid Tokenid { get;  set;}
  6. Public DateTime Regtime;
  7. public person child ;
  8. public person Friend;
  9. }

Members in a class are used only to distinguish between different types of variables. We serialize with JavaScriptSerializer and Json.NET, respectively:

  1. var person = New person
  2. {
  3. Age = 28,
  4. Name = "Li Yubao <yubaolee:>",//intentionally adding special characters
  5. Regtime = DateTime.Now,
  6. Tokenid = Guid.NewGuid (),
  7. Child = new person
  8. {
  9. Age = 1,
  10. Name = "Baby",
  11. Regtime = DateTime.Now,
  12. Tokenid = Guid.NewGuid ()
  13. }
  14. }; //Note the friend in this area is not assigned, default is empty
  15. JavaScriptSerializer serializer = new JavaScriptSerializer ();
  16. var jsstr = serializer.                Serialize (person); //Using JavaScriptSerializer serialization
  17. String newtonstr = Jsonconvert.serializeobject (person); //Using json.net serialization

JavaScriptSerializer serialization is done by an object, and then calls its member function serialize to serialize;

Json.NET is serialized directly using the provided static member Jsonconvert.serializeobject;

Both use is relatively simple, json.net call up convenient so a lost! Let's take a look at the console output:

Above the green for JavaScriptSerializer results, below the yellow background for the results of json.net, here are a few places to note:

1. JavaScriptSerializer the time format after serialization: "\/date (1441813200214)/" represents the total number of milliseconds of the difference between the January 1, 1970 (the minimum value of datetime) to the date actually represented by dates. Usually we need to turn it into a standard time format. You can do string processing in the following ways:

    1. Jsstr = Regex.Replace (jsstr, @"\\/date\ ((\d+) \) \\/", Match =
    2. {
    3. DateTime dt = new DateTime (1970, 1, 1);
    4. DT = dt. Addmilliseconds (long. Parse (match. GROUPS[1].  Value));
    5. DT = dt. ToLocalTime ();
    6. return dt.  ToString ("Yyyy-mm-dd HH:mm:ss");
    7. });

The effect after processing is complete:

Of course, you can also use the inherited JavaScriptConverter method, which is specifically mentioned in the following deserialization.

Json.NET the date generated by default is also inconvenient for the client to read and needs to be handled simply:

    1. String newtonstr = Jsonconvert.serializeobject (p, formatting.indented,
    2. New Isodatetimeconverter () {DateTimeFormat = "Yyyy-mm-dd HH:mm:ss"});

2, JavaScriptSerializer serialization will be special characters (such as <>, etc.) encoding, such as the above \u003c \u003e, a lot of people see this, the first feeling is too ripped, followed by a variety of Baidu, how to turn this into a normal " <> ". In fact, you do not have to do anything, this is the standard JS encoding, the front end will handle the problem on its own. Like what:

    1. <script type="Text/javascript" >
    2. var str = ' Yubaolee <yubaolee> '
    3. var str2 = ' Yubaolee \u003cyubaolee\u003e ';
    4. alert (str = = STR2); //result is true
    5. </script>

Attached: If you really don't understand \u003c what the hell is this thing, please go: character encoding.

As can be seen from the above two points, JavaScriptSerializer serialized JSON string is easy to cause some confusion, and json.net completely did not deal with the above two cases. So now a lot of people are using json.net, but from the point of view of the HTML standard, the results of JavaScriptSerializer serialization are more in line with the requirements of HTML. However, in order to operate the habit, it is recommended to use Json.NET.

Deserialization

We have two different ways to deserialize the two strings that have been successfully serialized:

    1. Deserializing a JavaScriptSerializer-generated string
    2. Using the JavaScriptSerializer method
    3. var Jsperson = serializer. Deserialize<person> (JSSTR);
    4. Using the Json.NET method
    5. var Newtonperson = jsonconvert.deserializeobject<person> (JSSTR);
    6. Deserializing a json.net-generated string
    7. var jsperson2 = serializer. Deserialize<person> (NEWTONSTR);
    8. var newtonperson2 = jsonconvert.deserializeobject<person> (NEWTONSTR);

Running will find that 4 of the deserialization code will work, and not as some previous predecessors said, JavaScriptSerializer serialized string can only be deserialized, json.net serialized string can only be deserialized with json.net.

It is not surprising that the deserialized string above is generated by the program and can be deserialized normally. But usually the strings that we want to deserialize are the strings that the client submits to the server, they are usually incomplete, or some of them will appear to be out of type. Like what:

    1. String nochildstr =
    2. "{\" name\ ": \" Li Yubao <yubaolee:>\ "," +
    3. "\" age\ ":" +
    4. "\" regtime\ ": \" 2015-09-11 00:10:48\ "," +
    5. "\" friend\ ": null}";
    6. var Jsperson = new JavaScriptSerializer ().  Deserialize<person> (NOCHILDSTR);
    7. var Newtonperson = jsonconvert.deserializeobject<person> (NOCHILDSTR);

Note that in this string, there is no tokenid, no child, and friend is null. Take a look at the results:

Two of them are smart! The results of the parsing are all what we want. But what if it looks like this?

    1. String nochildstr =
    2. "{\" name\ ": \" Li Yubao <yubaolee:>\ "," +
    3. "\" age\ ":" +
    4. "\" regtime\ ": \" 2015-09-11 00:10:48\ "," +
    5. "\" friend\ ": null," +
    6. "\" tokenid\ ": null}"; //Note that this tokenid is empty

At run time, the program will directly error.

The wrong content is easy to understand because we assign a null to the GUID type, and there is definitely an error. During the actual project operation, it is possible to pass a null-content string to a datetime type, pass a number to a GUID and other parameters, the key is that we have to deal with them, but not the program directly error crashes.

1. In JavaScriptSerializer, there is a javascriptconverter that can handle these problems, which is used to implement the processing of custom types in JSON serialization. The following code, for example, deals with the case of assigning a null value to a GUID:

  1. Public class Personjsconverter:javascriptconverter
  2. {
  3. public override object Deserialize (idictionary<string, object> dictionary, type type, JavaScriptSerializer serializer)
  4. {
  5. Person person = new Person ();
  6. object value = null;
  7. if (dictionary. TryGetValue ("Tokenid", out value) && value! = null)
  8. Person. Tokenid = (Guid) value;
  9. //Other fields slightly ...
  10. return person;
  11. }
  12. public override idictionary<string, object> Serialize (object obj, JavaScriptSerializer Serializer)
  13. {
  14. dictionary<string, object> dic = new dictionary<string, object> ();
  15. var node = obj as Person ;
  16. if (node = = null)
  17. return null;
  18. if (! String. IsNullOrEmpty (node. Name))
  19. Dic. ADD ("Name", node.)  Name);
  20. //Other fields slightly ...
  21. return dic;
  22. }
  23. public override ienumerable<type> Supportedtypes
  24. {
  25. Get
  26. {
  27. return new type[] { typeof (person)};
  28. }
  29. }
  30. }

Then, before deserializing, we register the transformation in the entity object, and then execute, and the program is all right:

    1. JavaScriptSerializer serializer = new JavaScriptSerializer ();
    2. Serializer.  Registerconverters (new javascriptconverter[] { new Personjsconverter (),});
    3. var deserialize = serializer. Deserialize<person> (NOCHILDSTR);

2, in the use of json.net, a more elegant way to deal with this problem--jsonconverter, it can handle a specified class member variable alone. This will not have to handle all members of the entire class like the javascriptconverter above. The code is as follows:

  1. Public class Guidconverter:jsonconverter
  2. {
  3. public override bool Canconvert (Type objectType)
  4. {
  5. return Objecttype.isassignablefrom (typeof (Guid));
  6. }
  7. public Override object Readjson (Jsonreader reader, Type objectType, object Existingvalue, Jsonserializer serializer)
  8. {
  9. Try
  10. {
  11. return serializer.  Deserialize<guid> (reader);
  12. }
  13. Catch
  14. {
  15. //If the value passed in causes an exception, an initial value is assigned
  16. return guid.empty;
  17. }
  18. }
  19. public override void Writejson (jsonwriter writer, object value, Jsonserializer serializer)
  20. {
  21. Serializer. Serialize (writer, value);
  22. }
  23. }

It is important to note that Jsonconverter is a attribute, so add an attribute to the class member:

  1. Public class person
  2. {
  3. public string Name;
  4. public int age;
  5. [Jsonconverter (typeof (Guidconverter))]
  6. Public Guid Tokenid { get;  set;}
  7. Public DateTime Regtime;
  8. public person child ;
  9. public person Friend;
  10. }

At this point, when you run the program again, the Tokenid will be assigned an initial value. It seems that in deserialization, json.net is still better.

Performance

This is a comparison of two performance on the Web:

In summary, use Json.NET for object serialization, regardless of the system's requirements for third-party control references.

Other common serialization methods

For a long while, review the definition of serialization:

serialization : The process of converting an object into a byte stream so that the object can be easily saved in a disk file or database.

Deserialization: The inverse process of serialization is the process of swapping byte streams back to the original object.

For other methods of serialization, please refer to:

Serialization and deserialization, and serialization of JSON deserialization

Talk about:. NET serialization and deserialization

JSON serialization that's a little bit of a thing

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.