using System.Text.Json.Serialization;
public static void Main()
static void TryDeserialize<T>(string json, string label)
var contact = JsonSerializer.Deserialize<T>(json);
Console.WriteLine($"{label}: OK, type = {contact}");
Console.WriteLine($"{label}: FAIL, message = {e.Message}");
var jsonNum = "{ \"type\": 1 }";
var jsonStr = "{ \"type\": \"Phone\" }";
TryDeserialize<Contact1>(jsonNum, "Contact1 (JsonPropertyName)");
TryDeserialize<Contact1>(jsonStr, "Contact1 (JsonPropertyName)");
TryDeserialize<Contact2>(jsonNum, "Contact2 (EnumMember)");
TryDeserialize<Contact2>(jsonStr, "Contact2 (EnumMember)");
TryDeserialize<Contact3>(jsonNum, "Contact3 (JsonStringEnumConverter)");
TryDeserialize<Contact3>(jsonStr, "Contact3 (JsonStringEnumConverter)");
[JsonPropertyName("type")]
public ContactType1? Type { get; set; }
public override string ToString() => Type?.ToString() ?? "null";
[JsonPropertyName(@"Email")]
[JsonPropertyName(@"Phone")]
[JsonPropertyName("type")]
public ContactType2? Type { get; set; }
public override string ToString() => Type?.ToString() ?? "null";
[System.Runtime.Serialization.EnumMember(Value = @"Email")]
[System.Runtime.Serialization.EnumMember(Value = @"Phone")]
[JsonPropertyName("type")]
[JsonConverter(typeof(JsonStringEnumConverter))]
public ContactType3? Type { get; set; }
public override string ToString() => Type?.ToString() ?? "null";