1

I'm trying to understand what is happening here. I am deserializing a JSON response with NewtonSoft.Json

I notice that I explicitly need to cast the properties of this dynamic type in order for them to be interpreted.

Example:

[Test]
public void Test()
{
    var a = JsonConvert.DeserializeObject<dynamic>("{ 'Amount': '123.0' }");

    Assert.AreEqual((decimal?)a.Amount, 123m);  //PASS
    Assert.AreEqual(a.Amount, 123m);            //FAIL
}

I'm interested to understand why this is happening?

Regards

Nagoh
  • 813
  • 2
  • 10
  • 23
  • Which is the nature of using dynamic objects. without the cast the compiler wont know what to do at run time to compare the two object. – Nkosi Mar 10 '17 at 02:32
  • Related though not identical: [Null-coalescing operator returning null for properties of dynamic objects](https://stackoverflow.com/questions/29051663/null-coalescing-operator-returning-null-for-properties-of-dynamic-objects/29053805#29053805). Basically `a.Amount` is a `JValue` and `JValue` has built-in dynamic support that enables explicit casting to `(decimal ?)` to work. – dbc Mar 10 '17 at 16:45

0 Answers0