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());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…