user2676140 user2676140 -4 years ago 76
C# Question

Parse JSON Array With C#

I am querying an API and returning data to a C# Console App. I am able to query my data successfully except for the array element of such. This is how the data is returned in JSON format

[
{
"UserType": "Admin",
"UserPerms:" [
{
"level1:" "Yes",
"level2:" "No",
"level3:" "No",
"level4:" "Yes",
"level5:" [
{
"door1:" "Yes",
"door2:" "No",
"door3:" "No",
"doory4:" "Yes"
}
]
}
]
}
]


And this is the C# syntax that I am trying to use to return the data - what is the proper C# syntax to return each door value for level5?

public class RootObject
{
public string UserType { get; set; }
public List<UserPerms> UserPerms { get; set; }
}
public class UserPerms
{
public string level1 { get; set; }
public string level2 { get; set; }
public string level3 { get; set; }
public string level4 { get; set; }
public string[] level5 { get; set; }
}

public class Main[]
{
var response = syncClient.DownloadString(url);
var o = JsonConvert.DeserializeObject<RootObject[]>(response);
foreach (RootObject ro in o)
if (ro.UserPerms != null)
foreach (UserPerms info in ro.UserPerms)
{
Console.WriteLine("Access to Level1" + info.level1);
Console.WriteLine("Access to Level2" + info.level2);
Console.WriteLine("Access to Level3" + info.level3);
Console.WriteLine("Access to Level4" + info.level4);
Console.WriteLine("Access to Level5" + info.level5);
}
}

Answer Source

The JSON for level5 displays a "list" of "key-value pair", so....

public List<Dictionary<string, string>> level5 { get; set; }

I'll try to come up with a fiddle soon.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download