c# - JsonSerializer.Deserialize 失败

标签 c# asp.net-core-mvc .net-core-3.1 system.text.json

考虑代码...

using System;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        int id = 9;
        string str = "{\"id\": " + id + "}";
        var u = JsonSerializer.Deserialize<User>(str);
        Console.WriteLine($"User ID: {u.Id}, Correct: {id == u.Id}");  // always 0/init/default value
    }
}


public class User {
    public int Id { get; set; }
}

为什么数据没有正确反序列化到 User目的?我还通过 DotNetFiddle 验证了该行为如果这是我系统的本地问题。不会抛出任何异常。

我的实际实现是从 [ApiController] 中读取的的 [HttpPost]行动后我return Created("user", newUser) .它通过 _httpClient.PostAsync 在我的 MVC/Razor 项目中调用.我在 Created 时验证了这些值是正确的已返回 PostAsync调用,但无论如何,从响应正文解析的值仅包含默认值(实际 ID 是 Guid )。

我最初认为这可能是与 UTF8 相关的问题,因为这是 StringContent 的编码。我发到 ApiController . UTF8反序列化引用here ,但我无法从 HttpContent 的 IO.Stream 获取到 ReadOnlySpanUtf8JsonReader .

我找到了 this project在搜索时,这让我认为它应该按我的预期工作。

最佳答案

你的问题是 System.Text.Json默认情况下区分大小写,所以 "id": 9 (全部小写)未映射到 Id属性(property)。来自 docs :

Case-insensitive property matching

By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set JsonSerializerOptions.PropertyNameCaseInsensitive to true:

Note: The web default is case-insensitive.

var options = new JsonSerializerOptions
{
   PropertyNameCaseInsensitive = true,
};
var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);

所以你也需要这样做:
var u = JsonSerializer.Deserialize<User>(str, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
演示 fiddle #1 here .
您可以在 ASP.NET Core 3.0 中配置启动时的选项,如 How to set json serializer settings in asp.net core 3? 所示。 :
services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
或者您可以申请 [JsonPropertyName("id")] 到您的模型:
public class User {
    [JsonPropertyName("id")]
    public int Id { get; set; }
}
演示 fiddle #2 here .

关于c# - JsonSerializer.Deserialize 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60123376/

相关文章:

c# - 检查用户是否具有角色 Discord.net

c# - 创建 ASP.NET Web 应用程序作为 Office 365 任务 Pane 加载项

c# - 预编译的 Azure 函数和 CloudTable 绑定(bind)输出不起作用

c# - ApiController 并不总是在 BadRequest 中返回数据

asp.net-core - 在 MVC 6 中将 [Authorize] 与 OpenIdConnect 一起使用会导致立即出现空 401 响应

c# - 异步方法调用是否应该在所有方法调用范围内链接起来?

c# - .NET Core 3.1 Worker Service - 环境特定配置

javascript - 将文件对象从 Javascript 传递到 Web API

asp.net-core-mvc - ASP.NET Core 2.2 - 操作过滤器数据库查询问题

asp.net-core-3.1 - 如何从 .net core 3.1 api 响应中删除 'Server' header ?