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"
    },

2 Answers 2

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#

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, totally missed that that way of doing it would allow me to pass the 'year' as a variable. Thanks again.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.