![](/img/trans.png)
[英]System.Text.Json: when deserializing, how can I ignore a null or empty string value for a property that has a default value set in the constructor?
[英]Put a default value if the string is null during deserializing
我有這樣的模型:
public class Artwork
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string @default { get; set; }
}
我使用此模型反序列化圖稿路徑。 當其中一個字符串為null時,我想放置一個默認路徑,這樣我仍然可以顯示圖片。 我試圖使用Json.NET庫中的一些屬性:
[DefaultValue("path/to/any/picture")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
但是當它反序列化時拋出“System.NullReferenceException”它不起作用。
當我在反序列化時獲得路徑並在路徑為空時顯示默認圖片時,如何設置顯示這些圖片?
我設法像這樣解決了我的問題
public class Artwork
{
private static string defaultAtwork = "https://pixabay.com/static/uploads/photo/2016/01/06/07/06/bokeh-1123696_960_720.jpg";
private string _small = defaultAtwork;
private string _medium = defaultAtwork;
private string _large = defaultAtwork;
private string _default = defaultAtwork;
public string small
{
get { return _small; }
set { _small = value; }
}
...
}
public class Album
{
private Artwork _artwork = new Artwork();
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public Artwork artwork
{
get { return _artwork; }
set { _artwork = value; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.