JSON值无法转换为System.Nullable[System.Int32]。

14

我将一个ASP.NET Core 2.2 API更新到ASP.NET Core 3.0,并且我正在使用System.Json:

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

我尝试使用之前可以正常工作的 Angular 8 发送 JSON 数据:

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

ASP.NET Core 3.0 API中的模型是:

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

而 API 控制器操作如下:

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

当我提交这个模型时,会出现以下错误:

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

在使用System.Json而不是Newtonsoft时,我需要做其他事情吗?


4
userId 是一个字符串。 - Daniel A. White
1
这个回答解决了你的问题吗?在使用System.Text.Json中的JsonConverter等效物 - Orace
4个回答

38

从ASP.NET Core 3.0开始,Microsoft已经移除了对Json.NET的依赖,并改用System.Text.Json命名空间来进行序列化、反序列化等操作。

但您仍然可以配置应用程序以使用Newtonsoft.Json。具体方法如下:

  1. 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包

  2. 在 ConfigureServices() 中调用 AddNewtonsoftJson() 方法-

    services.AddControllers().AddNewtonsoftJson();

更多信息请参见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


3
即使被接受的答案回答了问题,但这个答案更实用。 - Mukus
对我来说有效。谢谢。 - Sneha

12

在这里,您通过json传递字符串值给UserId,但您的模型引用一个int32?类型的值来表示UserId。那么你的值是如何从字符串转换为int32的呢?


4
我理解这一点,但使用Newtonsoft它被转换了... 我认为System.Json更加严格。 - Miguel Moura
1
设置 JSON 属性属性。 - BASKA

4
在我的情况下,我只发送了"",而不是null :)

2

我遇到了这个问题!所有的解决方案都对我无效!所以我做了以下操作:

  • 首先,返回给我的数据如下:
    enter image description here

    我需要将年份转换为整数,并将值转换为双精度浮点数! enter image description here
    你应该制作自定义的JsonConverter,经过了很多搜索后,它对我起作用了,这里是一个示例:

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();
    }
}

然后你可以将它保存到数据库中!随意尝试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接