Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read values from a Dynamic Object C#

I'm trying to read values from System.Web.Helpers.DynamicJsonObject. I can see the values in the debugger but I can't figure out how to access them. I have tried this

item.GetType().GetProperty("batch_id").GetValue(item, null);

but when I try that I get this response in the debugger "item.GetType().GetProperty("batch_id")' is null"

I have attached a picture from my solution enter image description here

Thank you, -Tesh

like image 765
MindGame Avatar asked Oct 16 '12 20:10

MindGame


People also ask

How do you dynamically access an object property in C#?

In C#, you can access dynamic properties by obtaining a PropertyObject reference from the specific object reference using the AsPropertyObject method on the object.

What is ExpandoObject in C#?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.

What is dynamic property in C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.

What is the difference between dynamic type variables and object type variables in C#?

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.


3 Answers

It is dynamic so you can just do:

string batchId = item.batch_id;

If for some reason you have the property name in a string, and don't know it at compile time, the indexing operator will work:

string value = item["batch_id"];
like image 153
driis Avatar answered Sep 29 '22 05:09

driis


Try enumerating the values DynamicJsonObject.GetDynamicMemberNames Method. It returns an IEnumerable of string.

like image 31
decyclone Avatar answered Sep 29 '22 05:09

decyclone


It doesn't work because they are fields, not properties. And, yeah, it is dynamic, so you can use just item.batch_id.

like image 28
Sergei B. Avatar answered Sep 29 '22 06:09

Sergei B.