JsonSerializer - serialize decimal places with 'N2' formatting

Chris picture Chris · Jul 26, 2013 · Viewed 17.3k times · Source

I'm serializing decimals using Newtonsoft.Json.JsonSerializer.

How can I set it to serialize decimal numbers with only 1 decimal place to use 0 at the end.

i.e. 3.5 serializes to "3.50"?

Answer

Cᴏʀʏ picture Cᴏʀʏ · Jul 26, 2013

You'll have to write your own custom JsonConverter and use it to intercept the decimal type so you can change how it gets serialized. Here's an example:

public class DecimalFormatConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(decimal));
    }

    public override void WriteJson(JsonWriter writer, object value, 
                                   JsonSerializer serializer)
    {
        writer.WriteValue(string.Format("{0:N2}", value));
    }

    public override bool CanRead
    {
        get { return false; }
    }

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

To use it, simply pass in a new instance of this custom converter to the SerializeObject method:

var json = JsonConvert.SerializeObject(yourObject, new DecimalFormatConverter());