Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonSerializer - serialize decimal places with 'N2' formatting

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"?

like image 431
Chris Avatar asked Jul 26 '13 02:07

Chris


1 Answers

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());
like image 135
Cᴏʀʏ Avatar answered Sep 20 '22 14:09

Cᴏʀʏ