C # dynamic json objects with a question about dynamic names

Before I get the checkbox for the duplicate, I have a code from a Dynamic json object with numeric keys , which works pretty well. The question with my number keys is that, unfortunately, the JSON string I get is initially limited by year, so I would use reflection to try to create a dynamic property for a dynamic object, and if so, how? I know with a dynamic object, I cannot have obj ["2010"] or obj [0]. This is not a problem in JavaScript, just an attempt to get it working in C #. Ideas? JSON return example:

{ "2010": [ { "type": "vacation", "alloc": "90.00" }, 

Alternatively, sometimes the year is the second element as such: I cannot control this json.

  { "year": [], "2010": [ { "type": "vacation", "alloc": "0.00" }, 
+4
source share
2 answers

I may not understand your question, but here's how I do it:

 static void Main(string[] args) { var json = @" { '2010': [ { 'type': 'vacation', 'alloc': '90.00' }, { 'type': 'something', 'alloc': '80.00' } ]}"; var jss = new JavaScriptSerializer(); var obj = jss.Deserialize<dynamic>(json); Console.WriteLine(obj["2010"][0]["type"]); Console.Read(); } 

Does it help?

I wrote a blog post about JSON serialization / deserialization with .NET: Quick JSON Serialization / Deserialization in C #

+5
source

I voted for the question and answer of JP, and I'm glad I dug on the Internet to find this.

I included a separate answer to simplify my use case for others. Its essence is as follows:

 dynamic myObj = JObject.Parse("<....json....>"); // The following sets give the same result // Names (off the root) string countryName = myObj.CountryName; // Gives the same as string countryName = myObj["CountryName"]; // Nested (Country capital cities off the root) string capitalName = myObj.Capital.Name; // Gives the same as string capitalName = myObj["Capital"]["Name"]; // Gives the same as string capitalName = myObj.Capital["Name"]; 

Now all this seems quite obvious, but I just did not think about it.

Thanks again.

+1
source

All Articles