4

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"
    },
Community
  • 1
  • 1
kpcrash
  • 350
  • 3
  • 13

2 Answers2

5

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#

JP Richardson
  • 38,609
  • 36
  • 119
  • 151
  • Thanks, totally missed that that way of doing it would allow me to pass the 'year' as a variable. Thanks again. – kpcrash Jul 29 '11 at 16:10
1

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.

Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86