I am calling a REST endpoint from C# and I am receiving json which gets serialized into an object. One of the properties on this object is a dynamic property. The value of the dynamic property is set as a anonymous object on the server site like this:
myObject.MyDynamicProp = new { Id = "MyId2134", Name = "MyName" };
On the client site the value of the dynamic property from the json serialization is a JObject containing the following value:
{{
"id": "MyId2134",
"Name": "MyName"
}}
I would have expected to be able to access the properties like this:
var s = myObject.MyDynamicProp.Name;
but it does not find the Name property instead I have to get the value like this:
var s = myObject.MyDynamicProp["Name"].Value;
I tried converting the JObject into a dynamic object like this but it returns JObject:
var dyn = myObject.MyDynamicProp.ToObject<dynamic>();
How can I convert the dynamic property value such that I can call its properties directly?
var s = myObject.MyDynamicProp.Name;
UPDATE ...
I ran the following
dynamic d = JsonConvert.DeserializeObject("{\"MyDynamicProp\": {\"id\": \"MyId2134\", \"Name\": \"MyName\"}}");
string name = d.MyDynamicProp.Name;
Which gives me the following the error:
{Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: `Newtonsoft.Json.Linq.JObject' does not contain a definition for `MyDynamicProp'
at Microsoft.Scripting.Interpreter.ThrowInstruction.Run (Microsoft.Scripting.Interpreter.InterpretedFrame frame) [0x00027]
I would like to add that this is an Xamarin iOS project and the code is located in a PCL library.
I assumed there was a problem with my code but it looks like it is not possible to use dynamic types within a Xamarin iOS project. https://developer.xamarin.com/guides/ios/advanced_topics/limitations/
It is actually quite easy. Instead of using var
use dynamic
on your JObject
and you will be fine:
dynamic do = myObject.MyDynamicProp;
string name = do.Name;
From your fragment:
dynamic d = JsonConvert.DeserializeObject("{\"MyDynamicProp\": {\"id\": \"MyId2134\", \"Name\": \"MyName\"}}");
string name = d.MyDynamicProp.Name;
Console.WriteLine(name); // writes MyName
Why this works: As Richard explained, JObject
derives indirectly from JToken
which implements IDynamicMetaObjectProvider
. It is that interface that allows dynamic
to work.
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