Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@kwestground kwestground commented Mar 10, 2016

For safer transformation use

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

This comment has been minimized.

Copy link

@AliaksandrBortnik AliaksandrBortnik commented Oct 4, 2017

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

@Bouke

This comment has been minimized.

Copy link
Owner Author

@Bouke Bouke commented Oct 5, 2017

Thanks to both of you!

@Nickman87

This comment has been minimized.

Copy link

@Nickman87 Nickman87 commented Aug 27, 2020

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
You can’t perform that action at this time.