How to localize when JSON-serializing?

The JSON standard for serializing decimal values does not provide for localized formatting. (See JSON.org.) This is why values are always formatted with the Invariant culture.

If you need localized values, then you’ll need to create a custom converter for your serializer of choice which outputs the decimals as pre-formatted strings instead. In Json.Net, this can be done easily as shown below:

class Program
{
    static void Main(string[] args)
    {
        List<decimal> values = new List<decimal> { 1.1M, 3.14M, -0.9M, 1000.42M };

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

        Console.WriteLine(json);
    }
}

class FormattedDecimalConverter : JsonConverter
{
    private CultureInfo culture;

    public FormattedDecimalConverter(CultureInfo culture)
    {
        this.culture = 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)
    {
        writer.WriteValue(Convert.ToString(value, culture));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Output:

["1,1","3,14","-0,9","1000,42"]

Leave a Comment