1

Before upgrade, the .Netcore version is 2.2, The string in JSON http request body can be converted to int in object like below Json


Post: api/ValidateMember
Host: XXXX
Content-Type: application/json

{
  "id": "125324"
}

to object:

class RequestWithID
{
  public int id {get;set;}
}
...
[HttpPost("api/ValidateMember")]
public bool ValidateMember(RequestWithID requestWithID)
{
...
}

This can work well before.

But after the .Netcore version upgrade to 3.1. there will always be an error with same request: The JSON value could not be converted to System.Int32. How to support the dynamic parsing of the string to int in .Netcore 3.1?

user13904118
  • 87
  • 1
  • 8

2 Answers2

2

Explanation

Starting from ASP.NET Core 3.0 System.Text.Json serializer is used by default instead of previous Newtonsoft.Json.

Even though Newtonsoft.Json is slower (link 1 & link 2) than System.Text.Json it has many more features thus, making it sometimes more fitting choice as you experienced yourself.

Solution

In order to bring back the Newtonsoft.Json serializer add Microsoft.AspNetCore.Mvc.NewtonsoftJson package reference to your project and call AddNewtonsoftJson() in your Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddNewtonsoftJson();
}

Also, when adding custom converters, ensure that you use Newtonsoft.Json namespace instead of System.Text.Json as both supply similarly named types.

Prolog
  • 2,698
  • 1
  • 18
  • 31
0

You can use JsonNumberHandlingAttribute and it handles everything correctly in 1 line, so you can keep using System.Text.Json (which is faster than Newtonsoft.Json)

[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public string Id { get; set; }
....

Per https://stackoverflow.com/a/59099589

Dave
  • 645
  • 7
  • 8