这是类数据库:JSON对象显示为空。为什么?
namespace vVvBot.Model
{
public class Database
{
public List<CustomCommand> CustomCommands { get; set; }
public List<CustomEvent> CustomEvents { get; set; }
}
}
这是自定义事件类:
namespace vVvBot.Model
{
public class CustomEvent
{
public string Name { get; set; }
public bool Enabled { get; set; }
public List<CustomCommand> Commands { get; set; }
}
}
这是类CustomCommand:
namespace vVvBot.Model
{
public class CustomCommand
{
public string Keyword { get; set; }
public CommandType Type { get; set; }
public string Message { get; set; }
public bool Enabled { get; set; }
}
}
这是我反序列化类序列化数据库对象
namespace vVvBot.Data
{
public class FileJsonContext
{
public Database ReadToObject(string fileName)
{
dynamic jsonData = File.ReadAllText(fileName);
return JsonConvert.DeserializeObject<Database>(jsonData) ?? new Database();
}
public void ObjectToFile(string fileName, Database database)
{
dynamic jsonData = JsonConvert.SerializeObject(database, Formatting.Indented);
File.WriteAllText(fileName, jsonData);
}
}
}
在有问题的文件,这就是我实例数据库:
private Database _database;
public Database Database => _database ?? (_database = JsonContext.ReadToObject("Commands.txt"));
这个问题行是:
var messageindex = Database.CustomEvents[index].Commands.FindLastIndex(x => x.Type == CommandType.Welcome);
它试图完成线,但立即返回,因为它涉及返回null。在应该调用customcommand列表的自定义事件中有一个List,以便我可以访问该对象。不知道它为什么回到NULL。
JSON文件包括:
{
"CustomCommands": [
{
"Keyword": "Hello",
"Type": 0,
"Message": "World",
"Enabled": true
},
{
"Keyword": "Test",
"Type": 0,
"Message": "test",
"Enabled": true
},
{
"Keyword": "greeting",
"Type": 3,
"Message": "this isnt a test ",
"Enabled": true
},
{
"Keyword": "leaving",
"Type": 4,
"Message": "Sorry to see you go ",
"Enabled": true
},
{
"Keyword": "faq",
"Type": 1,
"Message": "This is a FAQ TEST ",
"Enabled": true
},
{
"Keyword": "Hi",
"Type": 0,
"Message": "Hilo ",
"Enabled": false
},
{
"Keyword": "Hi",
"Type": 0,
"Message": "Hilo ",
"Enabled": false
}
],
"CustomEvents": [
{
"Name": "greeting",
"Enabled": true
},
{
"Name": "leaving",
"Enabled": true
}
]
}
在您共享的JSON字符串中,“CustomEvents”的项目没有设置属性“Commands”。所以当你反序列化时,没有任何自定义事件会有命令。它将是空列表,所以当你查询空列表时,你总是会得到NULL。 –
它不是从CustomCommands中提取所有项目吗?当在CustomEvents类中调用它时@ChetanRanpariya 我想要使用CustomCommands中的Already的值 –
它不会那样工作.... JSON反序列化不会基于其他属性初始化属性。它是基于JSON字符串中的值。这里'Database'对象将具有带有值的'CustomCommands'和'CustomEvents'属性,但'CustomEvents'的项目在'CustomCommands'属性中不具有值。 –