JsonSerializer - 序列与“N2”格式小数 [英] JsonSerializer - serialize decimal places with 'N2' formatting
本文介绍了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
,并用它来拦截小数
类型,这样你可以改变它如何被序列化。这里有一个例子:
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屋!
查看全文