在我的C#(V9).NET6应用程序中,我有一个带有以下成员变量的类:
private readonly List<Dictionary<ConsoleColor, ConsoleColor>> colours = new ()
{
new Dictionary <ConsoleColor, ConsoleColor> (),
new Dictionary <ConsoleColor, ConsoleColor> ()
};
我把它写在json中,在一个像这样的文件中:
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions {
WriteIndented = true,
Converters = {
new JsonStringEnumConverter (JsonNamingPolicy.CamelCase)
}
};
string json = JsonSerializer.Serialize (this.colours, options);
using StreamWriter stream = File.CreateText (filePath);
stream.Write (json);
但当我试着再读一遍这篇文章时,如下所示:
string json = File.ReadAllText (filePath);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
this.colours = JsonSerializer.Deserialize<List<Dictionary<ConsoleColor,ConsoleColor>>> (json,options);
我得到了一个例外:
"无法将JSON值转换为 System.Collections.Generic.Dictionary`2[System.ConsoleColor,系统控制台 colored颜色 ]. 路径:$[0].Blue|线号:2|BytePositionInLine:18.
我做错了什么?Json看起来像一个字符串--异常发生在反序列化(JsonSerializer.是非序列化)时.我认为它可能需要一个 colored颜色 的数字,而不是阅读文本,但我真的希望我的JSON是人类可读的(在必要时,可以编辑).
Json文件如下所示:
[
{
"blue": "gray",
"cyan": "gray",
"darkBlue": "darkGray",
"darkCyan": "darkGray",
"darkGreen": "darkGray",
"darkMagenta": "darkGray",
"darkRed": "darkGray",
"darkYellow": "darkGray",
"green": "gray",
"magenta": "gray",
"red": "gray",
"yellow": "gray"
},
{
"black": "black",
"blue": "gray",
"cyan": "gray",
"darkBlue": "darkGray",
"darkCyan": "darkGray",
"darkGreen": "darkGray",
"darkMagenta": "darkGray",
"darkRed": "darkGray",
"darkYellow": "darkGray",
"green": "gray",
"magenta": "gray",
"red": "gray",
"yellow": "gray"
}
]