JsonSerializer - serialize decimal places with 'N2' formatting

∥☆過路亽.° 提交于 2019-11-27 02:43:44

问题


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


回答1:


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());



回答2:


The accepted answer is correct, but expanding upon the comments on accepted answer:

If you want the decimals in your JSON to be numbers instead of strings, you need to use WriteRawValue and use :0.00 instead on :N2 for the string formatting (as N2 includes thousand separator commas and other culture specific number formatting that will break your JSON)

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.WriteRawValue($"{value:0.00}");
    }

    public override bool CanRead => false;

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

This is the difference in output compared to the accepted answer.

# writer.WriteRawValue($"{value:0.00}");
{
    "MyDecimal": 3.50,
    "MyBiggerDecimal": 12345.50
}

# writer.WriteValue($"{value:N2}");
{
    "MyDecimal": "3.50",
    "MyBiggerDecimal": "12,345.50"
}

Note - the accepted answer is correct for the OP's specific question i.e. serialize 3.5 to "3.50", but I got here wanting to serialize 3.5 to 3.50 (without the string quotes).



来源:https://stackoverflow.com/questions/17871720/jsonserializer-serialize-decimal-places-with-n2-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!