简体   繁体   English

C# ASP.NET WebApi (2/Core 3.1) 大数的 Json 序列化问题

[英]C# ASP.NET WebApi (2/Core 3.1) Problem with Json serialization of big numbers

I have an issue with big numbers (Int64/UInt64) being rounded by ASP.NET Json serialization.我有一个大数字 (Int64/UInt64) 被 ASP.NET Json 序列化四舍五入的问题。 This happens in ASP.NET WebApi2 (.NET 4.5.2) as well as in ASP.NET Core WebApi (Core 3.1).这发生在 ASP.NET WebApi2 (.NET 4.5.2) 以及 ASP.NET Core WebApi (Core 3.1) 中。

This my DTO-class:这是我的 DTO 课程:

public class TestDTO
{
    public IEnumerable<long> BigNumbers { get; set; }
}

This is my controller method:这是我的控制器方法:

[HttpGet]
public IHttpActionResult GetNumberTest()
{
    TestDTO dto = new TestDTO
    {
        BigNumbers = new long[]
        {
            121720000000004554,
            21720000000004554,
            1720000000004554,
            720000000004554,
        }
    };

    return Ok(dto);
}

And this is the result:这是结果:

{
  "bigNumbers": [
    121720000000004560,
    21720000000004550,
    1720000000004554,
    720000000004554
  ]
}

As you can see the first two numbers are rounded (first one being rounded up, second one down), the last two are not rounded.如您所见,前两个数字已四舍五入(第一个向上四舍五入,第二个向下四舍五入),后两个未四舍五入。 This, of course, can be fatal behaviour.当然,这可能是致命的行为。 How can I disable this behaviour?如何禁用此行为?

The strange thing is... when I serialize the DTO manually via Newtonsoft.Json (JsonConvert.SerializeObject), then the result is correct.奇怪的是......当我通过Newtonsoft.Json(JsonConvert.SerializeObject)手动序列化DTO时,结果是正确的。

I know it works when I serialize the numbers as strings, but that´s not a real solution to the problem in my opinion.我知道当我将数字序列化为字符串时它可以工作,但在我看来这不是问题的真正解决方案。 I should be able to rely on a correct serialization of my DTO.我应该能够依赖我的 DTO 的正确序列化。

Can anyone help me please?有人可以帮我吗?

As it turns out, the serialized raw data is correct.事实证明,序列化的原始数据是正确的。 It´s just the visualization of SwaggerUi / Firefox through JavaScript which causes the issue.只是 SwaggerUi / Firefox 通过 JavaScript 的可视化导致了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM