Home >Backend Development >C++ >How to Gracefully Handle Unknown Enum Values During JSON Deserialization?

How to Gracefully Handle Unknown Enum Values During JSON Deserialization?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 11:02:09743browse

How to Gracefully Handle Unknown Enum Values During JSON Deserialization?

Ignoring Unknown Enum Values During JSON Deserialization

When you deserialize JSON data into an enum, it's possible to encounter situations where the JSON property contains values that don't match any existing enum values. By default, this can cause errors.

TolerantEnumConverter to the Rescue

To handle this gracefully, you can use a custom JsonConverter called TolerantEnumConverter. This converter provides a flexible approach to handling unknown enum values by defining a set of rules:

  1. If the JSON value matches an existing enum value, it's used.
  2. If the enum is nullable and the JSON value is null, it's set to null.
  3. If the enum has a value called "Unknown," it's used.
  4. Otherwise, the first value of the enum is used.

Implementation Details

The TolerantEnumConverter handles both string and integer values in JSON. It checks for matches based on case-insensitive string comparisons or presence in the set of enum values.

Example Usage

To use the TolerantEnumConverter, annotate your enum properties with the [JsonConverter(typeof(TolerantEnumConverter))] attribute. Here's an example:

[JsonConverter(typeof(TolerantEnumConverter))]
enum Status
{
    Ready = 1,
    Set = 2,
    Go = 3,
}

Demo Application

The following demo application demonstrates how to use the TolerantEnumConverter to handle both non-nullable and nullable enums:

// Sample JSON data
string json = @"
{
    ""NonNullableStatusWithValidStringValue"" : ""Set"",
    ""NonNullableStatusWithInvalidStringValue"" : ""Blah"",
    ""NullableStatusWithValidStringValue"" : ""Go"",
    ""NullableStatusWithInvalidStringValue"" : ""Blah"",
}";

// Deserialize JSON data into Foo object
Foo foo = JsonConvert.DeserializeObject<Foo>(json, new JsonSerializerSettings
{
    Converters = { new TolerantEnumConverter() }
});

// Output the deserialized values
foreach (PropertyInfo prop in typeof(Foo).GetProperties())
{
    Console.WriteLine(prop.Name + ": " + (prop.GetValue(foo) ?? "(null)"));
}

Output:

NonNullableStatusWithValidStringValue: Set
NonNullableStatusWithInvalidStringValue: Ready
NullableStatusWithValidStringValue: Go
NullableStatusWithInvalidStringValue: (null)

Conclusion

The TolerantEnumConverter provides a convenient way to deserialize JSON data into enums without encountering errors for unknown values. It offers customizable behavior to suit your specific needs.

The above is the detailed content of How to Gracefully Handle Unknown Enum Values During JSON Deserialization?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn