kpcrash kpcrash - 5 months ago 114
JSON Question

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

Answer

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#