**已关闭。**此问题需要debugging details。目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
29天前关闭。
Improve this question的
我有图书馆应用程序时,有可能注册为新用户,添加一些书籍,借用他们和存款。我有JSON文件的问题,因为当我从它的数据,我不能使用foreach循环操作此数据。这是奇怪的,因为,当没有database.json文件,应用程序第一次创建它,每个操作都工作得很好.所以错误只发生在我有database.json文件,例如当我想再次运行此应用程序.当我删除database.json文件,应用程序再次开始正常工作.在我把我的代码的一些部分:
namespace LibraryManagementSystem
{
public class Library
{
public Dictionary<string, object> database;
public Library()
{
database = new Dictionary<string, object>
{
{ "books", new List<Book>() },
{ "users", new List<User>() { new User { Login = "admin", Password = "admin" } } },
{ "registry", new List<Registry>() }
};
Setup();
}
private void Setup()
{
string cwd = Directory.GetCurrentDirectory();
string databasePath = Path.Combine(cwd, "database.json");
if (File.Exists(databasePath))
{
string json = File.ReadAllText(databasePath);
database = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Console.WriteLine("Library successfully loaded!");
Console.WriteLine(JsonConvert.SerializeObject(database));
}
else if (!File.Exists(databasePath))
{
Console.WriteLine("I can't find database.json file from last session...");
Console.WriteLine("No problem :) I will create new one!");
string json = JsonConvert.SerializeObject(database);
File.WriteAllText(databasePath, json);
Console.WriteLine(JsonConvert.SerializeObject(database));
}
Console.WriteLine("Psst! I have hint for you :) there is list of avaliable users, please don't waste it!");
Console.WriteLine(JsonConvert.SerializeObject(database["users"]));
}
字符串
问题只发生在像foreach (User user in (List<User>)database["users"])
这样的行中,并且只有当我重新运行应用程序或我之前创建了JSON文件时才会发生。下面是json在database.json中的外观:
{
"books":[],
"users":[{"Login":"admin","Password":"admin"}],
"registry":[]
}
型
(我第一次运行她的应用程序时创建了它)
我尝试了一些JObject,JArray.我认为我在谷歌中找到的所有东西。即使我使用像get和Bard这样的聊天工具,即使他们也不能帮助我,告诉我代码看起来很好。我得到的错误消息是:nable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List
1条答案
按热度按时间n3schb8v1#
在序列化这3个字典条目时,序列化器将检测它们的属性(使用反射)并正确输出它们。
但是当它被格式化时,它不能这样做,因为它需要填充的 * Type * 是字典中的
List<object>
,而object
没有属性。这里最好的办法是摆脱Dictionary,使用具有实际属性的类,就像这样:
字符串
这里是如何使用它:
型
工作演示:https://dotnetfiddle.net/p434ye