Handling possible null value when converting JSON to C# class Handling possible null value when converting JSON to C# class json json

Handling possible null value when converting JSON to C# class


You can make an int nullable by adding a ?:

public class Image{    public int? height { get; set; }    public Uri url { get; set; }    public int? width { get; set; }}

Other than json2csharp.com, QuickType can also help you do this:

public partial class Image{    [JsonProperty("height")]    [JsonConverter(typeof(ParseStringConverter))]    public long? Height { get; set; }    [JsonProperty("width")]    [JsonConverter(typeof(ParseStringConverter))]    public long Width { get; set; }}

You have to add in the URL property yourself. QuickType also generates a bunch of other things for you as well, such as the ParseStringConverter custom JsonConverter.


If you're expecting null for your data, then use nullbale types. Change your class to:

public class Image {    public int? height { get; set; }    public Uri url { get; set; }    public int? width { get; set; }}


Another workable approach:

JsonConvert.SerializeObject(myObject,                             Newtonsoft.Json.Formatting.None,                             new JsonSerializerSettings {                                 NullValueHandling = NullValueHandling.Ignore                            });