Last active
May 24, 2024 04:00
Serialize decimal to string in Newtonsoft.Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
It is much simpler to do:
return (objectType == typeof(decimal) || objectType == typeof(decimal?))
Thanks to both of you!
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
For safer transformation use