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?