Skip to content

Instantly share code, notes, and snippets.

@tl-stefano-piva
Last active February 8, 2021 16:08
Show Gist options
  • Save tl-stefano-piva/0881e3b30ee3932348faae821443b2d7 to your computer and use it in GitHub Desktop.
Save tl-stefano-piva/0881e3b30ee3932348faae821443b2d7 to your computer and use it in GitHub Desktop.
#nullable enable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
var json = "[" +
"{ \"name\": \"Credito Padano\", \"type\": null, \"holder_names\":[ \"James\", \"Bond\", null ] }," +
"{ \"name\": \"Revolut\", \"holder_names\": null }" +
"]";
JsonSerializerOptions options = new()
{
// Ignore null values when serializing and deserializing reference types
IgnoreNullValues = true,
};
var accounts = JsonSerializer.Deserialize<List<Account>>(json, options);
foreach (var account in accounts)
{
// It is always safe to call account.HolderNames.Count because `null` will not be deserialized into it
// And the default behavior would be an empty list
Console.WriteLine($"Account {account.Name} has {account.HolderNames.Count} holder names");
// It is always safe to call ToLower() on the type since null will be ignored and default values is used instead
Console.WriteLine($"Account {account.Name} is of type: {account.Type.ToLower()}");
foreach (var holderName in account.HolderNames)
{
// `null` however will still deserialized if it is an item in a collection
// as if it is there it is by design :shrug:
Console.WriteLine($"-> Name: [{holderName?.ToUpper()}]");
}
}
public class Account
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("type")]
public string Type { get; set; } = "current";
[JsonPropertyName("holder_names")]
public List<string?> HolderNames { get; set; } = new();
}
#nullable restore
@tl-stefano-piva
Copy link
Author

tl-stefano-piva commented Feb 8, 2021

Output is

Account Credito Padano has 3 holder names
Account Credito Padano is of type: current
-> Name: [JAMES]
-> Name: [BOND]
-> Name: []
Account Revolut has 0 holder names
Account Revolut is of type: current

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment