Handling Null Value from JSON using EPPLUS

Elba 141 Reputation points
2021-06-15T03:18:16.52+00:00

I am using C# and reading a JSON array and then displaying the data in an excel file using EPPLUS

Here is what the JSON looks like for the item when they are not NULL

"recipient": [
            "B31"
        ],

Here is what the JSON returns when the two fields have a "NULL" value

"recipient": null,

This is how I declared it in my class

 public List<string> recipient { get; set; }

This is the function that reads the JSON

public static async Task<string> getDocs(string sessionID)
        {
            string lastResponse;
            using (var httpClient = new HttpClient())
            {
              using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://generic.com/api/v21.1/query"))
              {
                request.Headers.TryAddWithoutValidation("Authorization", sessionID);
                request.Headers.TryAddWithoutValidation("X-VaultAPI-DescribeQuery", "true");
                request.Headers.TryAddWithoutValidation("Accept", "application/json"); 
                request.Content = new StringContent($"q={Uri.EscapeDataString("SELECT id, name, recipient")}");
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); 
                   var response = await httpClient.SendAsync(request);
                    var contents = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(contents + "Start of success");
                    lastResponse = contents.ToString();
                    return lastResponse;
               }
            }
        }

This is the function that writes to Excel

private static async Task SaveExcel(string strDocsZero, FileInfo fileDocsZero)
    {

        var jDocsZero = JsonConvert.DeserializeObject<JDocsClass>(strDocsZero);

        foreach (var num in jDocsZero.data)
        {
            Console.WriteLine(" Doc Name " + num.name.ToString() + " Recipient " + num.recipient[0].ToString()  );
        }
        DeleteIfExists(fileDocsZero);
        using var package = new ExcelPackage(fileDocsZero);
        var ws = package.Workbook.Worksheets.Add(Name: "MainReport");
        var range = ws.Cells[Address: "A2"].LoadFromCollection(jDocsZero.data, PrintHeaders: true);
        range.AutoFitColumns();


        ExcelRange range_table = ws.Cells[2, 1, ws.Dimension.End.Row, ws.Dimension.End.Column];
        //add a table to the range
        ExcelTable tab = ws.Tables.Add(range_table, "Table1");
        //format the table
        tab.TableStyle = TableStyles.Medium2;

        await package.SaveAsync();
    }

Problem: I get an exception as follows: "Object reference not set to an instance of an object." whenever the program encounters a Null value in the recipient field

Question: How do I handle the null value in the "recipient" so that if recipient returns "Null" it is printed as an empty cell in Excel?

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,836 questions
{count} votes

Accepted answer
  1. Cheong00 3,476 Reputation points
    2021-06-15T03:40:40.393+00:00

    You may add condition to guard against null array:

        if (num.recipient == null || num.recipient.Count == 0)
        {
          num.recipient = new List<String>() { "" };
        };
    

    Of course the easiest way is not to use auto-property in declaration:

    private List<string> _recipient = new List<string>();

    public List<string> recipient
    {
    get { return _recipient; }
    set { _recipient = value; }
    }

    Note that you still have to check the .Count property of recipient before use it if you implemented this way.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.