Skip to content

Instantly share code, notes, and snippets.

@Bouke
Last active May 24, 2024 04:00
Serialize decimal to string in Newtonsoft.Json
public class StringDecimalConverter : JsonConverter
{
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal) || objectType == typeof(decimal?);
}
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(((decimal)value).ToString(CultureInfo.InvariantCulture));
}
}
@Nickman87
Copy link

Should you not check for null in your WriteJson method? As you also cover nullable decimals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment