使用C#解析JSON数组

时间:2017-06-12 18:31:25

标签: c# json

我正在查询API并将数据返回到C#控制台应用程序。我能够成功查询我的数据,除了这样的数组元素。这是以JSON格式返回数据的方式

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

这是我尝试用来返回数据的C#语法 - 返回level5的每个门值的正确C#语法是什么?

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);
            }
}

1 个答案:

答案 0 :(得分:1)

level5的JSON显示“键值对”的“列表”,所以....

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

我会尽快想出一个小提琴。