Handling possible null value when converting JSON to C# class

empty json string c#
.net core deserialize json to object

I've run into an interesting problem when converting API data to a C# class in UWP.

I have an API that returns image dimensions, like this:

{
    "height": "25",
    "width": "25"
}

I also have a class with properties that match the JSON data, generated by json2csharp.com.

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

And I am converting the JSON to a C# class using something like this:

dynamic JsonData = JObject.Parse(JsonString);
Image img = JsonData.ToObject<Image>();

However, if the API does not know the height or width, it returns null instead of an int, like this:

{
    "height": null,
    "width": "25"
}

This obviously causes an exception to throw, specifically this error message:

Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type 'System.Int32'

Is there some way to work around this or handle this scenario?

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.

NullValueHandling setting, This sample serializes an object to JSON with NullValueHandling set to Ignore so that properties with a default value aren't included in the JSON result. Sample. Assuming your full JSON is as you show, your JSON doesn't give simple name/value pairs for name and email. Instead it has a dictionary of indexed property objects, where each object has a label property with value equal to the name of property you seek, and an adjacent value property C# - Value cannot be null when deserializing JSON

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; }
}

Migrate from Newtonsoft.Json to System.Text.Json, Not supported, workaround is not practical or possible. If you rely on Deserialize JSON null literal to non-nullable value types, ⚠️ Not supported, workaround, sample Serialization; namespace SystemTextJsonSamples { public class (The corresponding null handling setting is JsonSerializerOptions. Null values in the JSON are ignored only if they are valid. Null values for non-nullable value types cause exceptions. Utf8JsonReader, Utf8JsonWriter, and JsonDocument. System.Text.Json.Utf8JsonReader is a high-performance, low allocation, forward-only reader for UTF-8 encoded JSON text, read from a ReadOnlySpan<byte> or ReadOnlySequence<byte>.

Another workable approach:

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

NullReferenceException Class (System), public class NullReferenceException : SystemException static void Main(string​[] args) { int value = Int32.Parse(args[0]); List<String> names; if (value > The attempt to initialize its values therefore thrown a NullReferenceException exception. NET, have a high-level exception handler that captures all errors to that the app  Specifies null value handling options for the . Member name Value Description; Include: 0: Include null values when serializing and deserializing objects.

I agree with the other answers that suggest nullable integers. This seems like the most clean approach. If nullable integers are no option, you could indeed try the NullValueHandling option and leave the integers at their default value. As a compliment to the other answers here, I have included a example that uses the NullValueHandling setting.

Fiddle (running example on dotnetfiddle)

Code

using System;
using Newtonsoft.Json;

public class Program
{
    private static string JsonWithNull = @"{ 'height': '25', 'width': null }";

    public static void Main()
    {
        var settings = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        Image image = JsonConvert.DeserializeObject<Image>(JsonWithNull, settings);

        Console.WriteLine("The image has a height of '{0}' and a width of '{1}'", image.height, image.width);
    }
}

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

Boolean.TryParse Method (System), Tries to convert the specified span representation of a logical value to its C# Copy. public static bool TryParse (ReadOnlySpan<char> value, out bool using System; public class Example { public static void Main() { string[] values = { null, String. Parse(String) · TrueString · FalseString · Parsing Other Strings in the . This sample serializes an object to JSON with T:Newtonsoft.Json.NullValueHandling set to Ignore so that properties with a default value aren't included in the JSON result.

Consider Newtonsoft.Json.NullValueHandling.Ignore option.

Jsonconvert.deserialize to class returns null, The "case" doesn't match. The JSON element names are lower case; the class properties are upper case (the fields are lower case and not  JSON To C Sharp Class Converter helps you to convert JSON to Csharp class online.

JSONObject, Object. processing.data. The values can be any of these types: Boolean , JSONArray , JSONObject , Number , String , or the JSONObject. or to convert values into a JSON text using the put and toString methods. It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value. This way, the users of you're class will always have to handle both cases, and, you'll never return null values because the null will be converted to an Option<Movie>.None. But the most important benefit is that your code will transmit the correct message just by reading the signature of the method.

Newtonsoft.Json NullValueHandling.Ignor doesn't ignore null values , I have this class with one optional field which I want to hide from JSON when it's even with a null value. public partial class Library { [Newtonsoft.Json. JsonSerializationException: 'Error converting value 0 to type 'System. In C# Null values, Null coalescing and IsNullOrEmpty methods are used for three various purposes and cases. In this post, we discussed in detail about these keywords of C#. However, Null Coalescing has certain advantages and disadvantages as well as if it is incorporated inside the code then it can decrease the number of lines of the code.

MySQL 8.0 Reference Manual :: 11.5 The JSON Data Type, Converting between JSON and non-JSON values · Aggregation of Prior to MySQL 8.0.13, a JSON column cannot have a non- NULL default value. Along with  c# - returns - Handling null objects in custom JsonConverter's ReadJson method newtonsoft json custom deserializer (1) I've got a Newtonsoft JSON.NET JsonConverter to help deserialize a property whose type is an abstract class.

Comments
  • If it is possible to get a null for your integers then declare them as nullable ints
  • Make you int variables Nullable