【发布时间】:2018-05-08 19:43:59
【问题描述】:
我正在尝试反序列化代表此类的 json 文件的一部分。
public class Command
{
[JsonRequired]
public string Name { get; set; }
[DefaultValue("Json!")]
public string Text { get; set; }
//[DefaultValue(typeof(Dictionary<string, string>))]
public Dictionary<string, string> Parameters { get; set; } = new Dictionary<string, string>();
}
其中两个属性是可选的:Text 和 Parameters。我希望它们填充默认值。
问题是我无法弄清楚如何让它对他们俩都有效。
- 如果我使用
DefaultValueHandling.Populate选项,则Text将被填充,但Parameters仍然是null。 - 如果我使用
DefaultValueHandling.Ignore,那么情况会相反。 - 如果我在
Parameters属性上设置[DefaultValue(typeof(Dictionary<string, string>))],它会崩溃。
问题:有没有办法让它适用于所有属性?
我想让它不为空,这样我就不必在代码的其他部分检查它。
我尝试过的演示:
void Main()
{
var json = @"
[
{
""Name"": ""Hallo"",
""Text"": ""Json!""
},
{
""Name"": ""Hallo"",
}
]
";
var result = JsonConvert.DeserializeObject<Command[]>(json, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Populate,
ObjectCreationHandling = ObjectCreationHandling.Reuse
});
result.Dump(); // LINQPad
}
【问题讨论】:
-
当它在字典上崩溃时你得到了什么异常?我想知道是不是因为你需要实例化一些东西而不仅仅是声明一个类型?
-
@BenHall 它说:
Could not cast or convert from System.RuntimeType to System.Collections.Generic.Dictionary'2[System.String,System.String].但我刚刚注意到我使用了错误的重载,有一个像Type, String这样的东西也让我卡住了,因为我不相信字典可以从字符串创建。
标签: c# json json.net json-deserialization