Skip to content

Instantly share code, notes, and snippets.

@Bouke
Last active August 27, 2020 10:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Bouke/aa00f3952e9690223f51 to your computer and use it in GitHub Desktop.
Save Bouke/aa00f3952e9690223f51 to your computer and use it in GitHub Desktop.
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));
}
}
@kwestground
Copy link

For safer transformation use

writer.WriteValue(((decimal)value).ToString(CultureInfo.InvariantCulture));

@AliaksandrBortnik
Copy link

It is much simpler to do:
return (objectType == typeof(decimal) || objectType == typeof(decimal?))

@Bouke
Copy link
Author

Bouke commented Oct 5, 2017

Thanks to both of you!

@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