Convert JObject to a dynamic object

I call the REST endpoint from C # and I get json that serializes to an object. One of the properties of this object is a dynamic property. The value of a dynamic property is set as an anonymous object on the server site as follows:

myObject.MyDynamicProp = new { Id = "MyId2134", Name = "MyName" }; 

On the client site, the value of the dynamic property from json serialization is a JObject containing the following value:

 {{ "id": "MyId2134", "Name": "MyName" }} 

I would expect to access the following properties:

 var s = myObject.MyDynamicProp.Name; 

but it does not find the Name property instead, I should get a value similar to this:

 var s = myObject.MyDynamicProp["Name"].Value; 

I tried converting a JObject into a dynamic object like this, but it returns a JObject:

 var dyn = myObject.MyDynamicProp.ToObject<dynamic>(); 

How can I convert the value of a dynamic property so that I can use it 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 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 a XAMAIN iOS project, and the code is in the PCL library.


I assumed that there was a problem with my code, but it seems that it is not possible to use dynamic types in a XAMARIN iOS project. https://developer.xamarin.com/guides/ios/advanced_topics/limitations/

+5
source share
1 answer

This is actually quite simple. Instead of var use dynamic on JObject and everything will be fine:

 dynamic do = myObject.MyDynamicProp; string name = do.Name; 

From your snippet:

 dynamic d = JsonConvert.DeserializeObject("{\"MyDynamicProp\": {\"id\": \"MyId2134\", \"Name\": \"MyName\"}}"); string name = d.MyDynamicProp.Name; Console.WriteLine(name); // writes MyName 

Why it works: as Richard explains, a JObject comes indirectly from a JToken that implements IDynamicMetaObjectProvider . This is an interface that allows dynamic to work.

+14
source

Source: https://habr.com/ru/post/1246923/


All Articles