Search code examples
servicestack-text

ServiceStack : Serialize long number to string


In my C# code, I have a long variable like

public long ID { get; set; }

Now when ServiceStack returns it to Web browser, it is serialized as

{ "id" : 97786707294275442 }

This is wrong because long has a range of 2^63 in C#

But in Javascript, Number.MAX_SAFE_INTEGER is 2^53-1, which is 9007199254740991

Because 97786707294275442 is greater than 9007199254740991, the number is rounded in JS.

Is it possible to let ServiceStack serialize long to string when its value is greater than Number.MAX_SAFE_INTEGER?


Solution

  • JsConfig<long>.RawSerializeFn = (long num) =>
                {
                    if (num > 9007199254740991L || num < -9007199254740991L)
                        return string.Format("\"{0}\"", num);
                    return num.ToString();
                };
    

    Is it the best way?