4

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; }
    }
dbc
  • 104,963
  • 20
  • 228
  • 340
  • Your code should work, UNLESS you have applied a `[JsonPropertyName]` attribute to the properties, then it doesn't. – Poul Bak Apr 27 '22 at 21:46
  • Can you please add minimal repro? Or at least show where and how do you deserialize content. – Guru Stron Apr 28 '22 at 08:16
  • I completed the questions with the answer of you question @GuruStron – Vinicius Tirabassi Apr 28 '22 at 17:19
  • There's a thread with a like problem, but I tried some solutions and none workes https://stackoverflow.com/questions/38728200/how-to-turn-off-or-handle- camelcasing-in-json-response-asp-net-core/72033170?noredirect=1#comment127302832_72033170 – Vinicius Tirabassi Apr 28 '22 at 17:23

3 Answers3

4

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
});
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 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? – Vinicius Tirabassi Apr 28 '22 at 19:34
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.

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.