|
| 1 | +using Newtonsoft.Json.Converters; |
| 2 | +using Newtonsoft.Json; |
| 3 | +using System; |
| 4 | +using System.Reflection; |
| 5 | + |
| 6 | +namespace Firebase.Auth.Requests.Converters |
| 7 | +{ |
| 8 | + /// <inheritdoc /> |
| 9 | + /// <summary> |
| 10 | + /// Defaults enum values to the base value if |
| 11 | + /// </summary> |
| 12 | + public class DefaultEnumConverter : StringEnumConverter |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// The default value used to fallback on when a enum is not convertable. |
| 16 | + /// </summary> |
| 17 | + private readonly int defaultValue; |
| 18 | + |
| 19 | + /// <inheritdoc /> |
| 20 | + /// <summary> |
| 21 | + /// Default constructor. Defaults the default value to 0. |
| 22 | + /// </summary> |
| 23 | + public DefaultEnumConverter() |
| 24 | + { } |
| 25 | + |
| 26 | + /// <inheritdoc /> |
| 27 | + /// <summary> |
| 28 | + /// Sets the default value for the enum value. |
| 29 | + /// </summary> |
| 30 | + /// <param name="defaultValue">The default value to use.</param> |
| 31 | + public DefaultEnumConverter(int defaultValue) |
| 32 | + { |
| 33 | + this.defaultValue = defaultValue; |
| 34 | + } |
| 35 | + |
| 36 | + /// <inheritdoc /> |
| 37 | + /// <summary> |
| 38 | + /// Reads the provided JSON and attempts to convert using StringEnumConverter. If that fails set the value to the default value. |
| 39 | + /// </summary> |
| 40 | + /// <param name="reader">Reads the JSON value.</param> |
| 41 | + /// <param name="objectType">Current type that is being converted.</param> |
| 42 | + /// <param name="existingValue">The existing value being read.</param> |
| 43 | + /// <param name="serializer">Instance of the JSON Serializer.</param> |
| 44 | + /// <returns>The deserialized value of the enum if it exists or the default value if it does not.</returns> |
| 45 | + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
| 46 | + { |
| 47 | + try |
| 48 | + { |
| 49 | + return base.ReadJson(reader, objectType, existingValue, serializer); |
| 50 | + } |
| 51 | + catch |
| 52 | + { |
| 53 | + return Enum.Parse(objectType, $"{defaultValue}"); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// <inheritdoc /> |
| 58 | + /// <summary> |
| 59 | + /// Validates that this converter can handle the type that is being provided. |
| 60 | + /// </summary> |
| 61 | + /// <param name="objectType">The type of the object being converted.</param> |
| 62 | + /// <returns>True if the base class says so, and if the value is an enum and has a default value to fall on.</returns> |
| 63 | + public override bool CanConvert(Type objectType) |
| 64 | + { |
| 65 | + return base.CanConvert(objectType) && objectType.GetTypeInfo().IsEnum && Enum.IsDefined(objectType, defaultValue); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments