gpt4 book ai didi

c# - 如何使用默认值填充可选的集合属性?

转载 作者:太空狗 更新时间:2023-10-29 23:20:12 25 4
gpt4 key购买 nike

我正在尝试反序列化表示此类的 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>();
}

其中两个属性是可选的:TextParameters .我希望它们填充有默认值。

问题是我不知道如何让它对他们都有效。

  • 如果我使用 DefaultValueHandling.Populate然后选项 Text将被填充但是 Parameters遗迹 null .
  • 如果我使用 DefaultValueHandling.Ignore那么它会反过来。
  • 如果我设置[DefaultValue(typeof(Dictionary<string, string>))]Parameters 上它会崩溃的属性(property)。

问题:有没有办法让它适用于所有属性?

我想让它不为空,这样我就不必在代码的其他部分检查它。


我尝试过的演示:

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
}

最佳答案

不是通过设置指定全局 DefaultValueHandling,而是使用 [JsonProperty] 属性为每个单独的属性设置 DefaultValueHandling :

public class Command
{
[JsonRequired]
public string Name { get; set; }

[DefaultValue("Json!")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string Text { get; set; }

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public Dictionary<string, string> Parameters { get; set; } = new Dictionary<string, string>();
}

然后,像这样反序列化:

var result = JsonConvert.DeserializeObject<Command[]>(json);

关于c# - 如何使用默认值填充可选的集合属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com