kpcrash
kpcrash

Reputation: 330

c# dynamic json objects with dynamic names question

Before I get flagged for duplicate, I have the code from Dynamic json object with numerical keys working quite well now. The question with my numeric keys is that unfortunately, the JSON string I am getting is initially delimited by year, so would I use reflection to attempt to create a dynamic property on a dynamic object, and if so how? I know with a dynamic object I can't have obj["2010"] or obj[0]. In JavaScript this is no problem, just trying to get it working in C#. Ideas? Example of JSON being returned:

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

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

    {
"year": [],
"2010": [
    {
        "type": "vacation",
        "alloc": "0.00"
    },

Upvotes: 4

Views: 1832

Answers (2)

Murray Foxcroft
Murray Foxcroft

Reputation: 13745

I have up-voted the question and JP's answer and am glad I dug around the internet to find this.

I have included a separate answer to simplify my use case for others to benefit from. The crux of it is:

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 it all seems quite obvious but I just did not think of it.

Thanks again.

Upvotes: 1

JP Richardson
JP Richardson

Reputation: 39395

Maybe I'm misunderstanding your question, but here's how I'd 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 this help?

I wrote a blog post on serializing/deserializing JSON with .NET: Quick JSON Serialization/Deserialization in C#

Upvotes: 5

Related Questions