Home > Software design >  Serialization in WEB .NET 5 Newtonsoft - last 2 digits deserialize incorrectly
Serialization in WEB .NET 5 Newtonsoft - last 2 digits deserialize incorrectly

Time:12-28

I have a small API where a request is POSTed, but one of the fields in a List gets deserialized incorrectly.

I have classes as it goes:

A class that's used to send some data to the API (just a list of IDs of type long, client-side app):

public class PostDTO 
{
  public List<long> Ids { get; set; }
}

Another class in API project that runs on the server:

public class RequestDTO
{
  public List<long> Ids { get; set; }
}

And now the main method in controller:

[HttpPost("v2/{testNumber}")]public async Task<IActionResult> PostV2(int someNumber, [FromBody] PostDTO receivedData)

{
    
}

I'm testing the thing using Swagger UI. When I post a JSON with some IDs in the list:

"Ids":{
        "$id": "2",
        "$values": [
            212701000000005615
        ]
    }

the receivedData has numbers that are filled with zeroes at the right side:

Example input:  212701000000005615
Example output: 212701000000005600

I've added this to the Swagger config:

services.AddControllers().AddNewtonsoftJson(x=> { x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; x.SerializerSettings.FloatParseHandling = Newtonsoft.Json.FloatParseHandling.Double; });

Got nugets - Newtonsoft.JSON, and Microsoft.AspNetCore.Mvc.NewtonsoftJson.

Why does it deserialize into those 00 at the end? I've tried decimal / double / float at the both sides and it doesn't work. But if I use string on the client side it somehow works. What can I do to achieve minimum changes to the code and make it work properly?

CodePudding user response:

Swagger UI sends requests using JavaScript, and those numbers fall outside of JavaScript's number range, that's why they are getting rounded. For more information, see:

You can still test the requests using another client, e.g. curl. Or you specifically need Swagger UI, a possible workaround is to change the type of Ids from List<long> to List<string>.

  • Related