Json.NET Special handling of 64-bit long-integer data

Source: Internet
Author: User

Many ASP. NET projects, especially those that use Ajax, often need to return data in JSON format. The NET Framework provides JSON serialization and deserialization tools starting with version 3.5, but the personal feel is not very useful, and later found a third-party newtonsoft.json to use. Later, in MVC4, Microsoft has used Json.NET (Newtonsoft.json) to process Json data by default.


JavaScript numeric precision is 32 bits, if the number of integers more than 32 bits, it will be treated as a floating point. In other words, if the JSON generated from the server, a value is a 64-bit integer, to the front-end JavaScript, and then back to the server, without any operation, there can be distortion. Do an experiment:


> var a = 123456789012345678> Console.log (a); 123456789012345680


The point is that database design often uses bigint (64-bit) integers as the primary key, which is a very important and unbiased data, such as a model:


C # Anonymous object new {    id:123456789012345678l,    name: "James"};


Converting to JSON output to the front end is:


{"id": 123456789012345678, "name": "James"}


The object output from Ajax is a little bad.


$.getjson ("/api/test"). Done (function (JO) {    console.log (jo);}); /Object {id:123456789012345680, Name: "James"}


Obviously, this object changes the value after the return to the server, will not find the primary key, or update to the wrong data, resulting in a difficult to find a huge bug.


The solution, of course, is that JavaScript has a very strong ability to handle strings, and it is possible to process a server-side 64-bit integer into a string type. However, json.net default is to handle a long as number type, if you want to work with a string type, you need to customize a jsonconverter.


Given that integers in hexadecimal look neat, a hexlongconverter is defined to convert the Long/ulong data to a string of 16 binary representations.


public class hexlongconverter:jsonconverter{public override void Writejson (Jsonwriter writer, object value, Jsonseri  Alizer serializer) {//due to canconvert filtering, data type can only be long or ulong//uniform converted to long type processing long v = value is ulong ? (long)        (ULONG) Value: (long) value; Writer.    WriteValue (v.tostring ("X16"));    } public override Object Readjson (Jsonreader reader, Type objectType, Object Existingvalue, Jsonserializer serializer) {//Get read hexadecimal string hex = reader.        Value As String; Call the ToInt64 extension to convert a string to a long//ToInt64 extension method with a long v = hex.        ToInt64 (Numberstyles.hexnumber, 0L); Convert V to actual required type ULONG or long (not converted) return typeof (ULONG) = = ObjectType? (object)    (ULONG) V:v; } public override bool Canconvert (type ObjectType) {//Handle only long and ulong two types of data switch (Objecttype.fullna            Me) {case ' System.Int64 ': Case "System.UInt64": return true;  Default              return false; }    }}


The above code uses a string extension method ToInt32:


public static class stringextention{public    static int ToInt32 (This string me, NumberStyles style,        int defaultval UE)    {        int? value = Me. ToInt32 (style);        return value = = null? Defaultvalue:value. Value;}    }


When serializing or deserializing a model, you only need to add the Hexlongconverter object as an argument:


Serialized string JSON = Jsonconvert.serializeobject (model, New Hexlongconverter ());//deserialization Somemodal model = Jsonconvert.deserializeobject<model> (JSON, new Hexlongconverter));



RELATED links:


[Json.NET]

    • http://json.codeplex.com/

    • Http://james.newtonking.com/json



This article from "Border Town Inn," the blog, please be sure to keep this source http://jamesfancy.blog.51cto.com/2516291/1409149

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.