考虑代码...
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 获取到 ReadOnlySpan
或 Utf8JsonReader
.我找到了 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
totrue
: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/