I am facing an issue by converting JSON to c# using JSON converter. where I have a field decimal and JSON has an exponential value which is not converting because decimal taking it as a string not as double:
Error: Could not convert string to decimal: 1.096E8
C#
public decimal Amount { get; set; }
JSON
"Amount":"1.096E8"
If you want to convert your exponential number by JsonConverter
then
public class MyClassName
{
[JsonConverter(typeof(JsonExponentialConverter))]
public decimal Amount { get; set; }
}
This is the json converter that convert your exponential number to decimal
public class JsonExponentialConverter : JsonConverter
{
public override bool CanRead { get { return true; } }
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
decimal amount = 0;
if (decimal.TryParse(reader.Value.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out amount))
{
return amount;
}
return amount;
}
}
And call above class with json deserializer like
public class Program
{
static void Main(string[] args)
{
var json = @"{'Amount':'1.096E8'}";
var amount = JsonConvert.DeserializeObject<MyClassName>(json);
}
}
Output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With