长解析不正确的JSON响应ASP.NET MVC [英] Long parsing incorrectly JSON response ASP.NET MVC

查看:84
本文介绍了长解析不正确的JSON响应ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个类:

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

在我的控制器中,我有以下称为方法的Ajax:

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);
     }

我的调用CustomFieldEdit的jQuery

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
            }
        });

因此控制器中的long值是-8454757700450211158,但解析为JSON的值是-8454757700450211000.

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

我知道我可以通过将custom_field_type_id更改为字符串或使用具有字符串属性的JSON DTO(用于长属性)来解决此问题,但是我想知道另一种解决此问题的方法,例如Newtonsoft JSON序列化程序设置. >

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.

推荐答案

我知道Javascript数字类型被限制为2 ^ 53(请参见例如

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.

这篇关于长解析不正确的JSON响应ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆