我試着去序列化我的字典裏,看起來像一本字典:序列化和反序列化包含類關鍵字
private Dictionary<MetaDataKey, User> _dictionary;
其中MetaDataKey和用戶類看起來像這樣:
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類用戶的領域。 即使我修復它manualy我仍然得到異常:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
當我試圖加載非空文件。 總之,2個問題: 1.糟糕的json節約。 2.壞JSON裝載
我們可以看到一個json文件包含的例子嗎? – maccettura
第一次是空的,我添加一個記錄後,我得到這個文件:{「WpfApplication2.MetaDataKey」:{「UserName」:「Enter Name」,「UserPassword」:「Enter Password」,「Accounts」: null}} (與iive發佈相同) –
它看起來像Newtonsoft JSON序列化程序使用鍵對象的ToString表示形式作爲鍵。默認的ToString表示是完整的類名(= namespace.classname)。 – ckuri