我将尝试对类似这样的字典进行序列化:
private Dictionary<MetaDataKey, User> _dictionary;
MetaDataKey和Users类看起来像这样:
internal class User
{
public string UserName { get; set; }
public string UserPassword { get; set; }
public List<Account> Accounts { get; set; }
}
internal class Account
{
public string Subject { get; set; }
public string AccName { get; set; }
public string AccPass { get; set; }
public List<string> Notes { get; set; }
}
internal class MetaDataKey
{
public string Name { get; set; }
public string Password { get; set; }
}
我将尝试将一个字典保存到json文件并从中加载,就像这样:
private void DictionaryInit()
{
//gets the dictionary file if exists, create an empty one if not.
string path = Directory.GetCurrentDirectory() + "\\dic.json";
if (!File.Exists(path))
{
_dictionary = new Dictionary<MetaDataKey, User>();
return;
}
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
_dictionary = JsonConvert.DeserializeObject<Dictionary<MetaDataKey, User>>(json);
}
}
public void DictionarySave()
{
//save the dictionary into dic.json file
string path = Directory.GetCurrentDirectory() + "\\dic.json";
string json = JsonConvert.SerializeObject(_dictionary);
File.WriteAllText(path, json);
}
当我在向字典加载新记录并尝试保存时,出现以下错误:
{"WpfApplication2.MetaDataKey":{"UserName":"Enter Name","UserPassword":"Enter Password","Accounts":null}}
改为:
{"WpfApplication2.MetaDataKey":{"Name":"Enter Name","Password":"Enter Password"},"WpfApplication2.User":{"UserName":"Enter Name","UserPassword":"Enter Password","Accounts":null}}
正如您所看到的,我正在从MetaDataKey类中获取Users字段。即使我手动修复它,仍然会出现异常:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
当我尝试加载一个非空文件时,出现了两个问题: 1. JSON保存不良。 2. JSON加载不良。