Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal is not converting exponential value ( jsonConverter from JSON to C#) - mapping

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"
like image 725
Dev Doc Avatar asked Sep 02 '25 03:09

Dev Doc


1 Answers

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:

enter image description here

like image 65
er-sho Avatar answered Sep 04 '25 22:09

er-sho