using Newtonsoft.Json; using System; namespace Discord.Net.Converters { internal class OptionalConverter : JsonConverter { private readonly JsonConverter _innerConverter; public override bool CanConvert(Type objectType) => true; public override bool CanRead => true; public override bool CanWrite => true; public OptionalConverter(JsonConverter innerConverter) { _innerConverter = innerConverter; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { T obj; // custom converters need to be able to safely fail; move this check in here to prevent wasteful casting when parsing primitives if (_innerConverter != null) { object o = _innerConverter.ReadJson(reader, typeof(T), null, serializer); if (o is Optional) return o; obj = (T)o; } else obj = serializer.Deserialize(reader); return new Optional(obj); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { value = ((Optional)value).Value; if (_innerConverter != null) _innerConverter.WriteJson(writer, value, serializer); else serializer.Serialize(writer, value, typeof(T)); } } }