How can I populate an optional collection property with a default value?

I am trying to deserialize a part of the json file representing this class.

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>();
}

where two properties are optional: Textand Parameters. I would like them to be filled with default values.

The problem is that I cannot figure out how to make it work for both of them.

  • If I use the parameter DefaultValueHandling.Populate, then it Textwill be filled, but Parameterswill remain null.
  • If I use DefaultValueHandling.Ignore, then it will be the other way around.
  • If I set [DefaultValue(typeof(Dictionary<string, string>))]in the property Parameters, it will work.

Quesiton : is there a way to make it work for all properties?

I would like to have this non-null, so I do not need to check it in another part of the code.


, :

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
}
+4
1

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);
+3

Source: https://habr.com/ru/post/1689798/


All Articles