Newtonsoft.Json C# CustomJsonConverter - to replace double seperator as per the culture passed

309 views Asked by At

All, trying to create a custom JsonConverter that changes the decimal seperator based on the culture passed as a parameter while serializing to a Json(similar to this).
Sample Console Application:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Globalization;

namespace TestJsonConverter
{
    class Program
    {

        class FormattedDecimalConverter : JsonConverter
        {
            private CultureInfo cultureinput;
            public FormattedDecimalConverter(CultureInfo culture)
            {
                this.cultureinput = culture;
            }
            public override bool CanConvert(Type objectType)
            {
                return (
                        objectType == typeof(decimal) ||
                        objectType == typeof(double) ||
                        objectType == typeof(float));
            }
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                var strValue = Convert.ToString(value, cultureinput);//String
                var doublevalue = Convert.ToDouble(strValue, cultureinput);//ConvertToDouble
                double doublevalueusingparse;
                Double.TryParse(strValue, NumberStyles.Any, cultureinput, out doublevalueusingparse);//TryParseToDouble


                writer.WriteValue(strValue);
                writer.WriteValue(doublevalue);
                writer.WriteValue(doublevalueusingparse);
            }
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                throw new NotImplementedException();
            }
        }
        static void Main(string[] args)
        {
            List<double> values = new List<double> { 1.02 };

            var converter = new FormattedDecimalConverter(CultureInfo.GetCultureInfo("nl-BE"));
            string json = JsonConvert.SerializeObject(values, converter);

            Console.WriteLine(json);
            Console.ReadLine();
        }
    }
}


Produces the following output:
["1,02",1.02,1.02]

Question: How to retain the comma seperator while writing the value as double? Writing the string produces a comma but while writing as a double its writer with a period.
Thanks in advance

1

There are 1 answers

0
SriramN On

As passing the double value with a comma in a Json will result in an invalid Json, the better options are to transfer the double value as a string like {"Sample": {"Text": "Sample", "Double": "10,12"}} or transfer it with a period. Will choose the string option here. Thanks for all the clarifications.