I have a class ChargesDetail
and am trying to deserialize json as shown below. Here I have used datatype that is Amount
.
public class ChargesDetail
{
public double DiscountRate { get; set; }
public Amount DiscountAmount { get; set; }
}
public class Amount:IConvertible
{
private double _val = 0;
private int _decimal = 5;
public Amount()
{
}
public Amount(double amount): this()
{
// this.Value = amount;
_val = Math.Round(amount, _decimal);
}
#region IConvertible Members
// Implementation snipped
#endregion
}
And my JSON looks like:
{ "DiscountRate":0.0, "DiscountAmount":0.0 }
Am trying to deserialize as like this:
T result = JsonConvert.DeserializeObject<ChargesDetail>(json);
It is giving me an exception like:
Invalid cast from 'System.Double' to 'Amount'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) at System.Double.System.IConvertible.ToType(Type type, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
How to deserialize json to this customized datatype?
- I cannot remove IConvertible, bcz it throws System.StackOverflowException in some calculations.
- I cannot change Amount type to double type, bcz there are more than 100 properties of same type and doing calculations in 'Amount' class.