我嘗試將以下 json 示例反序列化為 2D 字典。我首先在 www 和 stackoverflow 中尋找解決方案。我找到了許多 1D 解決方案以及宣告 2D 字典的答案,例如Dictionary<string, Dictionary<string, string>>
字串 fromFile.ReadAllText(path)讀取成功且正確JsonSerializer.Deserialize<myObject>(mystrWithJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })(在 Visual Studio 中使用斷點測驗)
我用 System.Text.Json
我的 Json 檔案看起來像這樣:
{
"One" : {
"OneOne" : "a directory path",
"OneTwo" : "a directory path"
},
"Two" : {
"TwoOne" : "a directory path",
"TwoTwo" : "a directory path"
}
"Three" : {
"ThreeOne" : "a directory path",
"ThreeTwo" : "a directory path"
}
我的班級看起來像這樣:
public class TwoDimDictionary
{
public IDictionary<string, IDictionary<string, string>> DirectoryPaths { get; set; }
public DirectoryEnviroment(IDictionary<string, IDictionary<string, string>> directoryPaths)
{
DirectoryPaths = directoryPaths;
}
}
主要任務是程式將添加或洗掉條目。因此,在這種情況下,“VS -> 編輯 -> 選擇性粘貼 -> Json”對我沒有幫助。如果程式關閉,條目將保存為 .json 檔案。代碼正在運行,但物件為空,所以它將是System.NullReferenceException: Object reference not set to an instance of an object.
任何想法或者只是我的json格式錯誤?
uj5u.com熱心網友回復:
使用 System.Text.Json 試試這個代碼
var dict= System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, Dictionary<string,string>>>(json);
string twoOne=dict["Two"]["TwoOne"];
結果
a directory path TwoOne
你必須修復你的json
{
"One": {
"OneOne": "a directory path",
"OneTwo": "a directory path"
},
"Two": {
"TwoOne": "a directory path TwoOne",
"TwoTwo": "a directory path"
},
"Three": {
"ThreeOne": "a directory path",
"ThreeTwo": "a directory path"
}
}
如果你想使用你的類,試試這個代碼
var dict= new TwoDimDictionary(
JsonSerializer.Deserialize<Dictionary<string, Dictionary<string,string>>>(json));
var twoOne=dict.DirectoryPaths["Two"]["TwoOne"];
public class TwoDimDictionary
{
public Dictionary<string, Dictionary<string, string>> DirectoryPaths { get; set; }
public TwoDimDictionary(Dictionary<string, Dictionary<string, string>> directoryPaths)
{
DirectoryPaths = directoryPaths;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397746.html
上一篇:使用dict格式化JSON
