![](/img/trans.png)
[英]JSon.Net JObject.FromObject Vs JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(obj));
[英]Set Default value for missing Complex properties with JSON.net (JsonConvert.SerializeObject or JsonConvert.DeSerializeObject)
我有一個要求,我需要使用JsonProperty
和DefaultValue
為以下復雜屬性Instances
設置默認值。
我知道我們可以為下面鏈接中提到的原始屬性實現這一點,但需要知道如何為復雜的屬性做到這一點。
下面是我需要使用DefaultValue()
設置的默認Instances
值。 請讓我知道如何實現這一目標。
要設置為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; }
}
如您所見,屬性僅支持常量值,因此您不能在屬性中設置復雜值。 如果要在反序列化過程中為復雜屬性設置默認值,一個好的方法是使用序列化回調方法,如下所示。
這個想法是向 class 添加一個方法,序列化程序將在 object 的反序列化完成后調用該方法。 回調必須是接受StreamingContext
作為其唯一參數的void
方法,並且必須使用[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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.