c#json读不发生

时间:2012-11-03 13:58:42

标签: c# json file

这不起作用(文件存在,它读取正常,然后没有循环触发),我不知道为什么......

if (File.Exists("my.json"))
{
    var response = System.IO.File.ReadAllText("my.json");
    var domains = JsonConvert.DeserializeObject<List<jsonRead>>(response);
    foreach (jsonRead domain in domains)
    {
        MessageBox.Show(domain.Password);
        var folders = JsonConvert.DeserializeObject<List<jsonReadDeep>>(domain.Folders);

        foreach (jsonReadDeep folder in folders)
        {
            MessageBox.Show(folder.localServer);                    
        }
    }
}

班级

class jsonRead
{
    public string Folders;
    public string Name;
    public string User;
    public string Password;
    public string Url;
}

class jsonReadDeep
{
    public string localFolder;
    public string serverFolder;
}

json

[   
  {
    "Folders": [
      {
        "localFolder": "C:\\test",
        "serverFolder": "Default/"
      }
    ],
    "Name": "hi",
    "User": "there",
    "Password": "secret",
    "Url": "https://mydomain.com"
  } 
]

1 个答案:

答案 0 :(得分:1)

您应该定义jsonRead,如下所示:

class jsonRead
{
    public jsonReadDeep[] Folders;
    public string Name;
    public string User;
    public string Password;
    public string Url;
}

你的代码:

var response = System.IO.File.ReadAllText("my.json");
var domains = JsonConvert.DeserializeObject<List<jsonRead>>(response);

foreach (jsonRead domain in domains)
{
    MessageBox.Show(domain.Password);

    foreach (jsonReadDeep folder in domain.Folders)
    {
        MessageBox.Show(folder.localFolder);
    }
}