JsonSerializer - 使用“N2"格式序列化小数位 [英] JsonSerializer - serialize decimal places with 'N2' formatting

查看:22
本文介绍了JsonSerializer - 使用“N2"格式序列化小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Newtonsoft.Json.JsonSerializer 序列化小数.

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

如何将其设置为序列化只有 1 个小数位的十进制数以在末尾使用 0.

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

即3.5 序列化为3.50"?

i.e. 3.5 serializes to "3.50"?

推荐答案

您必须编写自己的自定义 JsonConverter 并使用它来拦截 decimal 类型您可以更改它的序列化方式.举个例子:

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

要使用它,只需将此自定义转换器的新实例传递给 SerializeObject 方法:

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

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

这篇关于JsonSerializer - 使用“N2"格式序列化小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆