使用 JSON.netJsonConvert.SerializeObject 或 JsonConvert.DeSerializeObject为缺少的复杂属性设置默认值

问题描述

我有一个要求,我需要使用 InstancesJsonProperty 为下面的复杂属性 DefaultValue 设置默认值。

我知道我们可以为以下链接中提到的原始属性实现这一点,但需要知道我们如何为复杂的属性做到这一点。

Default value for missing properties with JSON.net

以下是我需要使用 Instances 设置的默认 DefaultValue() 值。请让我知道如何实现这一目标。

要设置为 Instances 属性的默认值:

Instance instance = new Instance();
instance.Name = "XYZ";
instance.MyProperty = 11;

List<Instance> Instances = new List<Instance>();
Instances.Add(instance);

代码片段:

public class DataSettings
{
  public DataSettings()
  {
    Instances = new List<Instance>();
  }

  [DefaultValue()] //How can I mention the above default value here ?
  [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
  public List<Instance> Instances { get; set; }
}

public class Instance
{
  public string Name { get; set; }
  public int MyProperty { get; set; }
}

解决方法

如您所见,属性仅支持常量值,因此您不能在属性中设置复杂值。如果要在反序列化过程中为复杂属性设置默认值,一个好的方法是使用 serialization callback 方法,如下所示。

这个想法是向您的类添加一个方法,序列化程序将在对象的反序列化完成后调用该方法。回调必须是接受 void 作为其唯一参数的 StreamingContext 方法,并且必须使用 [OnDeserialized] 属性进行标记。方法的名称无关紧要。 在回调方法中,您可以检查 Instances 列表是否已填充,如果没有,您可以根据需要设置默认值。

public class DataSettings
{
    public DataSettings()
    {
        Instances = new List<Instance>();
    }

    public List<Instance> Instances { get; set; }

    [OnDeserialized]
    internal void SetDefaultValuesAfterDeserialization(StreamingContext context)
    {
        if (Instances == null || !Instances.Any())
        {
            Instances = new List<Instance>
            {
                new Instance { Name = "XYZ",MyProperty = 11 }
            };
        }
    }
}

这是一个演示这个概念的工作小提琴:https://dotnetfiddle.net/uCGP5X

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...