The JSON value could not be converted to System.Nullable[System.Int32]
Asked Answered
S

3

14

I updated an ASP.NET Core 2.2 API to ASP.NET Core 3.0 and I am using System.Json:

services
  .AddMvc()
  .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
  .AddJsonOptions(x => {}) 

I then tried to post JSON data using Angular 8, which was working before:

{
  "name": "John"
  "userId": "1"
}

The model in the ASP.NET Core 3.0 API is:

public class UserModel {
  public String Name { get; set; }
  public Int32? UserId { get; set; } 
}

And the API Controller action is as follows:

[HttpPost("users")]
public async Task<IActionResult> Create([FromBody]PostModel) { 
}

When I submit the model I get the following error:

The JSON value could not be converted to System.Nullable[System.Int32]. 

Do I need to do something else when using System.Json instead of Newtonsoft?

Scenography answered 15/11, 2019 at 22:15 Comment(2)
userId is a string.Kumler
Does this answer your question? JsonConverter equivalent in using System.Text.JsonExotoxin
H
38

Microsoft has removed Json.NET dependency from ASP.NET Core 3.0 onwards and using System.Text.Json namespace now for serialization, deserialization and more.

You can still configure your application to use Newtonsoft.Json. For this -

  1. Install Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package

  2. In ConfigureServices() add a call to AddNewtonsoftJson()-

    services.AddControllers().AddNewtonsoftJson();

Read more on https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to

Housum answered 22/5, 2020 at 12:15 Comment(1)
This is the more useful answer even if the accepted answer is correct for the question.Antiphrasis
M
5

In my scenario I was just sending the "", not the null :)

Malissa answered 15/2, 2023 at 10:49 Comment(0)
S
2

I faced this issue! and all those solutions did not work for me! so I did the following:-

  • First of all the data returned to me as the following:-
    enter image description here

    I need to make year as an int and also want to make value as double! enter image description here
    You should make custom JsonConverter, it worked for me after a lot of search, and here is sample of:-

StringToDoubleConverter

public sealed class StringToDoubleConverter : JsonConverter<double>
{
    public override double Read(
        ref Utf8JsonReader reader,
        Type typeToConvert, 
        JsonSerializerOptions options)
    {
        double.TryParse(reader.GetString(),out double value);
        return value;
    }

    public override void Write(
        Utf8JsonWriter writer,
        double value, 
        JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

Then you can save it to db! play around as you like

Sewole answered 25/12, 2022 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.