Reputation: 1958
I know how to deserialize basic Json object. I am having a problem with nested objects; for example, here is an example json i want to deserialize.
{
"data": {
"A": {
"id": 24,
"key": "key",
"name": "name",
"title": "title"
},
"B": {
"id": 37,
"key": "key",
"name": "name",
"title": "title"
},
"C": {
"id": 18,
"key": "key",
"name": "name",
"title": "title"
},
"D": {
"id": 110,
"key": "key",
"name": "name",
"title": "title"
}
},
"type": "type",
"version": "1.0.0"
}
Now "data"
has an unknown number of objects, could be 100 could be 1000 or could be just 1 and all of them with different name. My ultimate goal is to get the information of each object inside data.
I tried basic json but didn't work at all.
Anyways, this is what I have tried...
I made class called data
public class data
{
public long id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
}
then I made another class called test
public class test
{
/*
I have also tried this, which works but then I don't know what to do with it and how to deserialize the information of it.
//public Newtonsoft.Json.Linq.JContainer data { get; set; }
*/
public List<List<data>> data { get; set; }
public string type { get; set; }
public string version { get; set; }
}
and in my driver application I did this
string downloadedData = w.DownloadString(link);
test t = JsonConvert.DeserializeObject<test>(downloadedData);
But this didn't work as I expected to. Any help would be appreciated.
Upvotes: 0
Views: 7926
Reputation: 4629
You are looking for a dictionary.
Use this as your class definition:
public class Rootobject
{
public Dictionary<string, DataObject> data { get; set; }
public string type { get; set; }
public string version { get; set; }
}
public class DataObject
{
public int id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
}
And this demonstrates that reading your object works:
var vals = @"{
""data"": {
""A"": {
""id"": 24,
""key"": ""key"",
""name"": ""name"",
""title"": ""title""
},
""B"": {
""id"": 37,
""key"": ""key"",
""name"": ""name"",
""title"": ""title""
},
""C"": {
""id"": 18,
""key"": ""key"",
""name"": ""name"",
""title"": ""title""
},
""D"": {
""id"": 110,
""key"": ""key"",
""name"": ""name"",
""title"": ""title""
}
},
""type"": ""type"",
""version"": ""1.0.0""
}";
var obj = JsonConvert.DeserializeObject<Rootobject>(vals);
Upvotes: 6