简体   繁体   中英

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. I tried to use some attribute from Json.NET library:

[DefaultValue("path/to/any/picture")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]

But it does not work, when deserializing it throws an "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; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM