无法在C#中对JSON文件进行操作[关闭]

nwwlzxa7  于 5个月前  发布在  C#
关注(0)|答案(1)|浏览(53)

**已关闭。**此问题需要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

n3schb8v

n3schb8v1#

在序列化这3个字典条目时,序列化器将检测它们的属性(使用反射)并正确输出它们。
但是当它被格式化时,它不能这样做,因为它需要填充的 * Type * 是字典中的List<object>,而object没有属性。
这里最好的办法是摆脱Dictionary,使用具有实际属性的类,就像这样:

public class MyDatabase
{
    public List<Book> Books { get; set; }
    public List<User> Users { get; set; }
    public List<Registry> Registry { get; set; }
}

字符串
这里是如何使用它:

var database = new MyDatabase
{
    Books = new List<Book>(),
    Users = new List<User>() { new User { Login = "admin", Password = "admin" } },
    Registry = new List<Registry>()
};

// Save data:
var json = JsonConvert.SerializeObject(database);

// Load data:
var newDb = JsonConvert.DeserializeObject<MyDatabase>(json);
Console.WriteLine("Login from deserialized database: " + newDb.Users[0].Login);


工作演示:https://dotnetfiddle.net/p434ye

相关问题