Reputation: 2528
If I have a decimal that represents some Japanese Yen (i.e. exponent zero currency) amount e.g. 3131313, I see Json.NET serialising the value to 3131313.0 by default.
Is there any way to get it to serialise the literal value 3131313 instead?
Upvotes: 1
Views: 1294
Reputation: 116188
By implementing your own converter you can serialize as
var str= JsonConvert.SerializeObject(
new {s="aaa",d=(decimal)3131313},
new MyConverter());
-
public class MyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(decimal)) return true;
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(Convert.ToInt64(value));
}
}
Upvotes: 1