长解析错误的JSON响应ASP.NET MVC

本文关键字:响应 ASP NET MVC JSON 错误 | 更新日期: 2023-09-27 18:21:47

我定义了一个类:

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

在我的控制器中,我有以下Ajax调用的方法:

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

我的jQuery调用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
            }
        });

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

我知道我可以通过将custom_field_type_id更改为字符串或为长属性创建一个具有字符串属性的JSON DTO来解决这个问题,但如果可能的话,我想知道另一种解决方法,比如Newtonsoft JSON序列化程序设置。

长解析错误的JSON响应ASP.NET MVC

我知道Javascript Number类型限制为2^53(例如。http://cdivilly.wordpress.com/2012/04/11/json-javascript-large-64-bit-integers/)所以你可能会遇到这个问题。为了避免遇到这个问题,我倾向于不将longs序列化到Json,所以我建议切换。

经过一点研究,我发现JavaScript中的最大整数值是2^53==9 007 199 254 740 992,你可能想把它改为float类型,看看浏览器端的反应。

如果它将被视为数字,那么它应该会解决您的问题。

这看起来像是一个已知的问题,它是Javascript的限制。您需要将其表示为字符串,以后可以用作Number类型。这里有一个快速链接供您参考。http://tinyurl.com/lr2o88w

另一个参考是http://ecma262-5.com/ELS5_HTML.htm#Section_8.5

看起来您正试图在JavaScript中使用JSON——如果不使用字符串,就不可能保持长字段的精确值。

为什么:所有的JavaScript引擎都使用等价的C#"double"作为"Numeric"类型(有关详细信息,请参阅JavaScript是否具有双浮点数字精度?)。该格式为值提供了52位,因此您无法在不损失一些精度的情况下表示long值的整个范围。