0

I have the following configuration in our dotnet 6 web application, and I would like to use Json.Net serialization.

services.AddControllersWithViews(ConfigureMvcOptions)
            .AddNewtonsoftJson(options =>
            {
                options.UseMemberCasing();
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.Culture = Thread.CurrentThread.CurrentCulture;
                options.SerializerSettings.Error += (sender, args) => throw args.ErrorContext.Error;
            });

It is not working as I expected if I try to deserialize a decimal number like this: 99 999

The number is valid in our culture settings because we are using the " " as decimal separator instead of comma.

If I directly set the CultrureInfo for Json.Net, the deserialization work as expected. options.SerializerSettings.Culture = new CultureInfo("hu-HU");

I already checked that the Thread.CurrentThread.CurrentCulture is hungarian when the exception throw by Json.Net. (throw args.ErrorContext.Error)

What I have missed? I know that I can write a custom serialization, howerver it would be nice if I could use the Json.Net serialization. I would not use System.Text.Json (I tried anyway with the same result) because we are upgrading a dotnet 4 MVC application.

dbc
  • 104,963
  • 20
  • 228
  • 340
Bohanon
  • 21
  • 6
  • 2
    I would suggest not using culture-specific notations for transporting values in JSON, if at all possible. – ProgrammingLlama Dec 21 '21 at 09:00
  • 1
    since it is a legacy application upgraded to .net core not easy to find where we send posts with / or without different UI settings. We are supporting multiple languages. Maybe we should use invariant settings when we transport data with JSON. I am going to check how many places should we change it. Thank you the suggestion – Bohanon Dec 21 '21 at 11:08
  • Json.NET does not use `SerializerSettings.Culture` when deserializing numbers because such JSON would be **malformed**. The [JSON standard](https://json.org/) has a simple invariant format for numbers that is the same as the c# invariant culture's format, and so Json.NET uses that. (`SerializerSettings.Culture` gets used for things like dates that Json.NET serializes as strings.) – dbc Jan 05 '22 at 23:36
  • But if the numbers are actually represented as localized **strings** in the JSON you could use a custom converter to deserialize them. See [How to localize when JSON-serializing?](https://stackoverflow.com/q/4721143/3744182) and [Handling decimal values in Newtonsoft.Json](https://stackoverflow.com/q/24051206/3744182). But what exactly does your JSON file look like? Can you share a [mcve]? – dbc Jan 05 '22 at 23:40
  • https://www.rfc-editor.org/rfc/rfc7159#section-6 – Hans Passant Jan 06 '22 at 01:41

0 Answers0