[英]Long parsing incorrectly JSON response ASP.NET MVC
我定义了一个类:
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序列化程序设置。
我知道Javascript Number类型限制为2 ^ 53(例如http://cdivilly.wordpress.com/2012/04/11/json-javascript-large-64-bit-integers/ )所以你可能遇到了问题。 我倾向于不把序列化为Json以避免遇到这个问题,所以我建议切换。
看起来你正试图在JavaScript中使用那个JSON - 不可能在不诉诸字符串的情况下保持长字段的精确值。
原因:所有JavaScript引擎都将等效的C#'double'用作“数字”类型(有关详细信息,请参见JavaScript是否具有双精度浮点数精度? )。 格式为您提供52位的值,因此您不能在不失去一些精度的情况下表示全范围的long
值。
经过研究,我发现JavaScript中的最大整数值为2 ^ 53 == 9 007 199 254 740 992,可能您想将其更改为浮点类型并查看浏览器端的反应。
如果它将被视为数字,那么它应该解决您的问题。
它看起来像一个已知的问题,它是Javascript的限制。 您需要将其表示为字符串,以后可以用作Number类型。 这是一个快速链接,供您参考。 http://tinyurl.com/lr2o88w
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.