Newtonsoft.Json deserializeObject不能在所有生成的键中获取值.&l



在web端,它显示了我添加了多少文件和文件夹,但在c#端,我无法获得文件和文件夹。

{
"name": "updater",
"type": "folder",
"path": "updater",
"items": [
{
"name": "tas",
"type": "folder",
"path": "updater/tas",
"items": [
{
"name": "sdsadsd.txt",
"type": "file",
"path": "updater/tas/sdsadsd.txt",
"byte": 6
},
{
"name": "tass",
"type": "folder",
"path": "updater/tas/tass",
"items": []
},
{
"name": "trexs.txt",
"type": "file",
"path": "updater/tas/trexs.txt",
"byte": 14
}
]
},
{
"name": "tas2",
"type": "folder",
"path": "updater/tas2",
"items": []
},
{
"name": "tas3",
"type": "folder",
"path": "updater/tas3",
"items": []
},
{
"name": "tas4",
"type": "folder",
"path": "updater/tas4",
"items": []
}
]
}

c#的一面

public class jsonFF
{
public string name { get; set; }
public string type { get; set; }
public string path { get; set; }
public jsonFF[] items { get; set; }
public long byt { get; set; }
}
private void start_Click(object sender, EventArgs e)
{
try
{
WebClient updt = new WebClient();
var updtJsonDownload = updt.DownloadString("http://localhost/update/updater.php");
jsonFF[] json = JsonConvert.DeserializeObject<jsonFF[]>(updtJsonDownload.ToString());
foreach (var item in json)
{
string sss = item.name;
log.Text += sss + Environment.NewLine;
}
}
catch (Exception ex)
{
log.Text = ex.ToString();
}
}

我想做的是我想做一个工具,将自动获取文件和文件夹作为json,并检查它们是否在计算机上的c#端或应该下载和更新它们。

您的等效类在这里是错误的。我已经用工具得到了等效类。Item类应该有byt属性,Root类也应该有items作为列表(在您的情况下,您有其类型的对象)

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Item
{
public string name { get; set; }
public string type { get; set; }
public string path { get; set; }
public List<Item> items { get; set; }
public int? byt { get; set; }
}
public class Root
{
public string name { get; set; }
public string type { get; set; }
public string path { get; set; }
public List<Item> items { get; set; }
}

你必须修复你的jsonFolder类。取代"对象项";List项目";(或";jsonFolder [] items")

jsonFolder[] items = JsonConvert
.DeserializeObject<jsonFolder>(updtJsonDownload.ToString()).items;
foreach (var item in items)
{
string sss = item.name;
log.Text += sss + Environment.NewLine;
}
//or shorter
log.Text=string.Join("n", items.Select(i =>i.name ));
//if you need file names
log.Text = string.Join("n", items.SelectMany(i =>i.items.Select(it =>it.name ) ))); 
//if you need  pathes
string[] pathes = items.SelectMany(i =>i.items.Select(it =>it.path)).ToArray();
public class jsonFolder
{
public string name { get; set; }
public string type { get; set; }
public string path { get; set; }
public List<jsonFolder> items { get; set; }
public int? byt { get; set; }
}

最新更新