[英]Put a default value if the string is null during deserializing
I have a model like this: 我有这样的模型:
public class Artwork
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string @default { get; set; }
}
I use this model to deserialize artwork path. 我使用此模型反序列化图稿路径。 When one of these strings is null I want to put a default path so I can still display a picture. 当其中一个字符串为null时,我想放置一个默认路径,这样我仍然可以显示图片。 I tried to use some attribute from Json.NET library: 我试图使用Json.NET库中的一些属性:
[DefaultValue("path/to/any/picture")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
But it does not work, when deserializing it throws an "System.NullReferenceException". 但是当它反序列化时抛出“System.NullReferenceException”它不起作用。
How can I manage to display these pictures when I get a path when deserializing and display a default picture when the path is null? 当我在反序列化时获得路径并在路径为空时显示默认图片时,如何设置显示这些图片?
I managed to solve my problem doing like this 我设法像这样解决了我的问题
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.