StealthRT StealthRT - 3 months ago 53
C# Question

JSON DeserializeObject with Class RootObject

Hey all I have the following json string:

{
"status":{
"msg":"Success",
"code":0,
"version":"1.0"
},
"metadata":{
"music":[
{
"external_ids":{ },
"label":"Atlantic Records",
"release_date":"2010-09-13",
"album":{
"name":"Passion, Pain & Pleasure"
},
"title":"Bottoms Up",
"duration_ms":"242013",
"genres":[
{
"name":"R&B\\Soul\\Funk"
}
],
"acrid":"63b14329c3beafe35cf08b144a2b4a31",
"result_from":3,
"artists":[
{
"name":"Trey Songz"
}
]
}
],
"timestamp_utc":"2016-08-18 13:56:40"
},
"result_type":3
}


That I am trying to get the following properties:

label
album > name
title
duration_ms
genres > name
artists > name


The C# code I have is:

dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject<mReconize.musicJsonReturn.RootObject>(json);
Console.WriteLine(data["metadata"]["music"].label);


Naturally the data["metadata"]["music"].label is causing an error but i'm not sure as to why?


Additional information: Cannot apply indexing with [] to an expression of type 'mR.musicJsonReturn.RootObject'


enter image description here

Answer

Try:

Console.WriteLine(data.metadata.music[0].label);

You don't work with an array but an object.

And never ever use dynamic.