Home >Backend Development >C++ >How to Handle Unknown Enum Values During JSON Deserialization with Json.net?

How to Handle Unknown Enum Values During JSON Deserialization with Json.net?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 13:27:41928browse

How to Handle Unknown Enum Values During JSON Deserialization with Json.net?

Ignoring Unknown Enum Values During JSON Deserialization

Problem:

JSON deserialization with Json.net can throw exceptions when encountering unknown enum values in JSON data. This occurs when an enum is created based on current documentation, but the third-party API later adds new enum values.

Solution: Custom JsonConverter

To resolve this issue, a custom JsonConverter can be used. Here's how it works:

  • If the JSON value matches the enum (string or integer), it's used.
  • If the enum is nullable, the value is set to null.
  • If the enum has an "Unknown" value, it's used.
  • Otherwise, the first value of the enum is used.

Code Implementation:

class TolerantEnumConverter : JsonConverter
{
    ... (Implementation from the provided answer)
}

Usage:

Apply the [JsonConverter(typeof(TolerantEnumConverter))] attribute to the enum type to use the custom converter during deserialization:

[JsonConverter(typeof(TolerantEnumConverter))]
enum Status
{
    ... (Enum values)
}

Example Demonstration:

The following code snippet demonstrates the use of the TolerantEnumConverter with different enum values and JSON inputs:

string json = @"
{
    ... (JSON data with valid and invalid enum values)
}";

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

foreach (PropertyInfo prop in typeof(Foo).GetProperties())
{
    object val = prop.GetValue(foo, null);
    Console.WriteLine(prop.Name + ": " + 
                     (val == null ? "(null)" : val.ToString()));
}

Output:

The console output shows how the TolerantEnumConverter handles unknown enum values, including setting values to "(null)", "Unknown", or using the first value of the enum.

The above is the detailed content of How to Handle Unknown Enum Values During JSON Deserialization with Json.net?. 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