Newtonsoft.Json Deserialization From Different Cultures

Viewed 9

I have an application which can receive JSON configuration in any culture format. To this end I am trying to use the culture property of the optional JsonSerializerSettings parameter to try reading a JSON from a different culture.

In this case I am use it-IT culture as an example which uses a comma for the decimal symbol, period for the digits grouping, and a semi colon to separate lists.

I first try to serialize a sample class into the it-IT culture but the serialized JSON still seem to use a period for the decimal (my own culture) as opposed to a comma (as per the specified it-IT culture).

Next I tried to de-serialize a simple JSON written in the it-IT culture but it throws an exception seemingly not accepting the it-IT format.

My test code is as follows:

        // Test class having a single float value
        private class MyClass
        {
            public float num { get; set; } = 2.5f;
        }
        // Main test class which tries serialization and deserialization to the it-IT culture
        static void Main(string[] args)
        {
            try
            {
                // Get the it-IT culture and display its number format
                CultureInfo culture = CultureInfo.GetCultureInfo("it-IT");
                Console.WriteLine("Name: " + culture.DisplayName);
                Console.WriteLine("Lists: " + culture.TextInfo.ListSeparator);
                Console.WriteLine("Decimal: " + culture.NumberFormat.NumberDecimalSeparator);
                Console.WriteLine("Negative: " + culture.NumberFormat.NegativeSign);
                Console.WriteLine("Positive: " + culture.NumberFormat.PositiveSign);
                Console.WriteLine("Grouping: " + culture.NumberFormat.NumberGroupSeparator);
                Console.WriteLine();
                // Attempt to serialize a myClass instance. Expecting number format to use comma.
                MyClass content = new MyClass();
                string json = JsonConvert.SerializeObject(content, new JsonSerializerSettings() { Culture = culture });
                Console.WriteLine(json);
                Console.WriteLine();
                // Attempt to de-serialize a json string in the it-IT culture  
                content = JsonConvert.DeserializeObject<MyClass>("{\"value\": 2,5}", new JsonSerializerSettings() { Culture = culture });
                Console.WriteLine(content.ToString());
                Console.WriteLine();
            }
            catch (Exception x) { Console.WriteLine(x); }
            Console.ReadLine();
        }

According to the information about the culture property in the optional JsonSerializerSettings parameter, this value is supposed to set the culture of the input when reading or culture of the output when writing.

Does anyone know what I am doing wrong that is seemingly causing the culture information to be ignored?

0 Answers
Related