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

时间:2014-09-15 01:01:52

标签: c# jquery asp.net asp.net-mvc json

我定义了一个类:

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

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

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

看起来您正在尝试在JavaScript中使用该JSON - 无法在不诉诸字符串的情况下保持长字段的精确值。

为什么:所有JavaScript引擎都使用相同的C#' double'作为"数字"类型(有关详细信息,请参阅Does JavaScript have double floating point number precision?)。格式为您提供了52位的值,因此您无法在不失一些精度的情况下表示全范围的long值。

答案 2 :(得分:2)

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

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

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

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