Last active
February 8, 2021 16:08
-
-
Save tl-stefano-piva/0881e3b30ee3932348faae821443b2d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is