I have tried use camelCase insentive on .NET 6 for deseralize content from API
I configured like this in Startup.cs, but it is not working
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.IgnoreNullValues = true;
});
I get to solve with this resolution: https://github.com/andre-ss6 https://github.com/dotnet/runtime/issues/31094#issuecomment-543342051
He recommended using the following code:
((JsonSerializerOptions)typeof(JsonSerializerOptions)
.GetField("s_defaultOptions",
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic).GetValue(null))
.PropertyNameCaseInsensitive = true;
I tried and worked, but I thought is complex, because it is used reflection, I don't know what to thought, Someone have other solution or a explanation?
I deserialize it like this:
var content = await response.Content.ReadAsStringAsync(cancellationToken);
var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content);
My class is, how can you saw, I don't use the attribute [JsonPropertyName]
public class InvestimentFundsResponseData
{
public IEnumerable<InvestmentFundsResponse> Data { get; set;}
}
public class InvestmentFundsResponse
{
public Guid Id { get; set; }
}
[JsonPropertyName]
attribute to the properties, then it doesn't. – Esplanade