我已经尝试在 .NET 6 上使用 camelCase insentive 来反序列化来自 API 的内容
我在 Startup.cs 中这样配置,但它不起作用
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.IgnoreNullValues = true;
});
我用这个分辨率来解决:https://github.com/andre-ss6 https://github.com/dotnet/runtime/issues/31094#issuecomment-543342051
他推荐使用下面的代码:
((JsonSerializerOptions)typeof(JsonSerializerOptions)
.GetField("s_defaultOptions",
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic).GetValue(null))
.PropertyNameCaseInsensitive = true;
我试过了,但我觉得很复杂,因为它使用了反射,我不知道该怎么想,有人有其他解决方案或解释吗?
我这样反序列化它:
var content = await response.Content.ReadAsStringAsync(cancellationToken);
var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content);
我的类是,你怎么看到的,我不用属性[JsonPropertyName]
public class InvestimentFundsResponseData
{
public IEnumerable<InvestmentFundsResponse> Data { get; set;}
}
public class InvestmentFundsResponse
{
public Guid Id { get; set; }
}
最佳答案
JsonSerializer.Deserialize
不使用由 AddJsonOptions
配置的 JsonSerializerOptions
,手动创建和传递所需的选项(可能从 DI 解析)通过 JsonOptions
):
var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = {new JsonStringEnumConverter()},
IgnoreNullValues = true
});
关于c# - .NET 6 - 带有 CamelCase 的 AddJsonOptions 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72034017/