我嘗試在 .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; }
}
uj5u.com熱心網友回復:
JsonSerializer.Deserialize不使用JsonSerializerOptions由 配置的AddJsonOptions,手動創建和傳遞所需選項(可能通過 DI 從 DI 決議JsonOptions):
var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = {new JsonStringEnumConverter()},
IgnoreNullValues = true
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/467284.html
