Brian Ogden
Brian Ogden

Reputation: 19212

Long parsing incorrectly JSON response ASP.NET MVC

I have a class defined:

 public class custom_field
{
    public long custom_field_type_id { get; set; }
}

In my controller I have the following Ajax called method:

    [HttpPost]
    public JsonResult CustomFieldEdit(long hash)
    {
           var respObj = new custom_field();
           respObj.custom_field_type_id = -8454757700450211158L;

           return Json(respObj);
     }

My jQuery that calls CustomFieldEdit

 var baseUrl = '@Url.Action("CustomFieldEdit")?hash=' + customFieldId;

 $.ajax({
            type: "POST",
            url: baseUrl,
            contentType: "application/json",
            data: JSON.stringify({ hash: customFieldId }),
            error: function (xhr, status, error) {
                toastr.error("Error saving, please try again.");
            },
            success: function (data) {
                console.log(data.custom_field_type_id); //error here! val = -8454757700450211000
            }
        });

So the long value in the controller is -8454757700450211158 but the value parsed to JSON is -8454757700450211000.

I know I can fix this by changing custom_field_type_id to a string or creating a JSON DTO with a string property for long properties but I would like to know another way for fixing this if possible, like a Newtonsoft JSON serializer setting.

Upvotes: 2

Views: 2824

Answers (3)

Mike Lanzetta
Mike Lanzetta

Reputation: 361

I know Javascript Number type is limited to 2^53 (see e.g. http://cdivilly.wordpress.com/2012/04/11/json-javascript-large-64-bit-integers/) so you could be running into that issue. I tend to not serialize longs to Json to avoid running into this issue, so I'd recommend switching.

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

It looks like you are trying to use that JSON in JavaScript - not possible to keep precise value of long field without resorting to string.

Why: all JavaScript engines use equivalent of C# 'double' as "Numeric" type (see Does JavaScript have double floating point number precision? for details). The format gives you 52 bits for value, so you can't represent full range of long values without loosing some precision.

Upvotes: 2

codebased
codebased

Reputation: 7073

After researching a bit, I found that The maximum integer value in JavaScript is 2^53 == 9 007 199 254 740 992 and probably you want to change that to float type and see the reaction of browser side.

If it will consider as Number then it should fix your problem.

It looks like a known issue and it is the limitation of a Javascript. you would need to represent this as a string and later can be used as a Number type. Here is a quick link for your reference. http://tinyurl.com/lr2o88w

Another reference is http://ecma262-5.com/ELS5_HTML.htm#Section_8.5

Upvotes: 2

Related Questions