.NET 6 - AddJsonOptions with CamelCase not working
Asked Answered
N

3

5

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; }
    }
Nasopharynx answered 27/4, 2022 at 19:1 Comment(4)
Your code should work, UNLESS you have applied a [JsonPropertyName] attribute to the properties, then it doesn't.Esplanade
Can you please add minimal repro? Or at least show where and how do you deserialize content.Dandrea
I completed the questions with the answer of you question @GuruStronNasopharynx
There's a thread with a like problem, but I tried some solutions and none workes https://mcmap.net/q/278875/-how-to-turn-off-or-handle-camelcasing-in-json-response-asp-net-core camelcasing-in-json-response-asp-net-core/72033170?noredirect=1#comment127302832_72033170Nasopharynx
D
5

JsonSerializer.Deserialize does not use JsonSerializerOptions which are configured by AddJsonOptions, create and pass required options manually (possibly resolve ones from the DI via JsonOptions):

var result = JsonSerializer.Deserialize<InvestimentFundsResponseData>(content, new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    Converters = {new JsonStringEnumConverter()},
    IgnoreNullValues = true
});
Dandrea answered 28/4, 2022 at 17:40 Comment(1)
Perfect!! But anyway, Did exist some way that I can to configure JsonSerializerOptions for the all project? If else I'll always that have pass as parameter, correct?Nasopharynx
S
1

I had the same issue, so I removed System.Net.Json 5.0.2 and reinstalled the version 6.0.2 this solved it for me.

Skim answered 2/9, 2022 at 12:11 Comment(0)
K
1

You could also make a JsonSerializerOptions singleton and add that to DI:

// Add this to the ConfigureServices routine in Startup.cs:
JsonSerializerOptions serializerOptions = new JsonSerializerOptions()
{
    PropertyNameCaseInsensitive = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    MaxDepth = 10,
    ReferenceHandler = ReferenceHandler.IgnoreCycles,
    WriteIndented = true
};
serializerOptions.Converters.Add(new JsonStringEnumConverter());
services.AddSingleton(s => serializerOptions);

Then to use, simply inject it into the constructor. That way, one change to the options is carried through all your code.

Note: I updated the options to be compliant with the latest version of System.Text.Json (6.0.9) and added a few that I usually specify. The default MaxDepth is 3, so if you have deeper parent/child relationships than that it'll miss some data.

Kalagher answered 6/10, 2022 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.