Avoid nulls in C# Class

Jassim Al Rahma 1,526 Reputation points
2022-02-26T12:01:01.767+00:00

Hi,

I have the following class which gets the data from MySQL database.

class SigninData
{
    public string user_id { get; set; }
    public string user_uuid { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string email_address { get; set; }
    public string country { get; set; }
}

But in some cases, the country will return null then my code will crash with the following error:

System.ArgumentNullException has been thrown

on this line:

List<SigninData> data = System.Text.Json.JsonSerializer.Deserialize<List<SigninData>>(result);

How can I avoid this?

Thanks,
Jassim

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,390 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,201 Reputation points
    2022-02-26T12:18:41.477+00:00

    See Microsoft Learn Ignore individual properties which shows several variants code samples also.

    Edit

    See if this works for you

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Text.Json;  
    using System.Text.Json.Serialization;  
      
    namespace DeserializeAvoidNullConsoleApp  
    {  
        class Program  
        {  
            private static string _fileName = "data.json";  
            static void Main(string[] args)  
            {  
                Write();  
      
                var list = Read();  
      
                foreach (var data in list)  
                {  
                    Console.WriteLine($"{data.first_name, -10}{data.country, -10} {(data.country is null)}");  
                }  
      
                Console.ReadLine();  
            }  
      
            private static List<SigninData> Read()   
                => JsonSerializer.Deserialize<List<SigninData>>(File.ReadAllText(_fileName));  
      
            private static void Write()  
            {  
                List<SigninData> signinData = new()  
                {  
                    new () { country = null, first_name = "Bob", last_name = "Smith", email_address = "bob@gmail", user_id = "A1", user_uuid = "Whatever" },  
                    new () { country = "Germany", first_name = "Anne", last_name = "Smith", email_address = "A@gmail", user_id = "B1", user_uuid = "XXXX" }  
                };  
      
                var options = JsonSerializerOptions();  
                  
                File.WriteAllText(_fileName, JsonSerializer.Serialize(signinData, options));  
      
            }  
      
            private static JsonSerializerOptions JsonSerializerOptions() =>  
                new ()  
                {  
                    WriteIndented = true,  
                    Converters = { new NullToEmptyStringConverter() }  
                };  
        }  
      
        class SigninData  
        {  
            public string user_id { get; set; }  
            public string user_uuid { get; set; }  
            public string first_name { get; set; }  
            public string last_name { get; set; }  
            public string email_address { get; set; }  
            public string country { get; set; }  
        }  
      
        public class NullToEmptyStringConverter : JsonConverter<string>  
        {  
            public override bool HandleNull => true;  
            public override bool CanConvert(Type typeToConvert)   
                => typeToConvert == typeof(string);  
            public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)   
                => throw new NotImplementedException();  
            public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)  
            {  
                writer.WriteStringValue(value ?? "");  
            }  
        }  
    }  
    

    Json

    [  
      {  
        "user_id": "A1",  
        "user_uuid": "Whatever",  
        "first_name": "Bob",  
        "last_name": "Smith",  
        "email_address": "bob@gmail",  
        "country": ""  
      },  
      {  
        "user_id": "B1",  
        "user_uuid": "XXXX",  
        "first_name": "Anne",  
        "last_name": "Smith",  
        "email_address": "A@gmail",  
        "country": "Germany"  
      }  
    ]  
    

    178102-figure1.png

    0 comments No comments

  2. AgaveJoe 26,166 Reputation points
    2022-02-26T12:36:06.95+00:00

    A null or empty country value should no cause an error with the JsonSerializer. I suspect there are other issues with your code that you have not share with the community. For example trying to access country members without checking if the variable is null.

    item.country?.Trim()  
    

    [Null-conditional operators ?. and ?
    ?? and ??= operators (C# reference)

    Example code

    static void Main(string[] args)  
    {  
        List<SigninData> mockQueryResults = new List<SigninData>()  
        {  
            new SigninData() {  
                email_address = "hello@world.com",  
                first_name = "hello",  
                last_name = "world",  
                user_id = "1",  
                user_uuid ="11",  
                country = null  
            },  
            new SigninData() {  
                email_address = "foo@bar.com",  
                first_name = "foo",  
                last_name = "bar",  
                user_id = "2",  
                user_uuid ="22",  
                country = "USA"  
            }  
        };  
      
        string result = JsonSerializer.Serialize<List<SigninData>>(mockQueryResults);  
        Console.WriteLine(result);  
        List<SigninData> data = JsonSerializer.Deserialize<List<SigninData>>(result);  
      
        foreach(var item in data)  
        {  
            Console.WriteLine($"user_id:\t{item.user_id}");  
            Console.WriteLine($"user_uuid:\t{item.user_uuid}");  
            Console.WriteLine($"first_name:\t{item.first_name}");  
            Console.WriteLine($"last_name:\t{item.last_name}");  
            Console.WriteLine($"email_address:\t{item.email_address}");  
            Console.WriteLine($"country:\t{item.country?.Trim()}");  
            Console.WriteLine();  
        }  
    }  
    
    0 comments No comments

  3. Bruce (SqlWork.com) 57,891 Reputation points
    2022-02-26T15:38:37.347+00:00

    The easiest fix is to define initial values in class definition. Then set ignore null in the json serialization.

    https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-6-0

    0 comments No comments