C # Json Dynamic Object

I work with a dynamic object .

Here is what I use to get data from an object:

string = obj.item.today.price; 

This works great, the problem is that as soon as I start using the numbers example:

 string = obj.daily.10000; 

It gives me an error

Is there any way to fix this?

+4
source share
2 answers

This is not possible for a " call 10000 on daily object " just because 10000 NOT a valid identifier .

Let me explain what happens here:

JSON parser generates some type of runtime inherited from some basic JSON type (e.g. JsonObject ). So obj is some kind of generated type, you call the item property on it, it returns the same generated type, then you call the today property, etc.

The last step is strange, there cannot be a 10000 property for any type generated or not.

But, if the library supports access to objects with a key, you can try to write

 obj.daily["10000"] 

or apply obj to a JObject (suppose you are using JSON.NET) and call the Property :

 var jsonObject = (JObject) obj; var propertyValue = jsonObject.Property("10000").Value; 
+3
source

If you are using Json.NET

 string json = "{ dayly : { 1000 : 'asd' } }"; dynamic d = JsonConvert.DeserializeObject(json); Console.WriteLine((d.dayly as JObject).Property("1000").Value); 
+1
source

All Articles