3

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?

Helen
  • 87,344
  • 17
  • 243
  • 314
saiyadjin
  • 33
  • 5

1 Answers1

1

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>.

Helen
  • 87,344
  • 17
  • 243
  • 314
  • Interesting. Thanks for the answer, didn't even think it could be that. I'm no JS programmer and swagger is used just to test different API calls. Interestingly enough it works in another client. Thank you for the answer – saiyadjin Dec 27 '21 at 19:52