2

I have two Json Converters, one converts dates as MM/dd/yyyy, and another as MM/dd/yy. Second converter (listed in the code example first) is always ignored, and the first one used. Is there a way to have multiple converters for DateTime, and use one on some pages, and another on other pages.

public class MmddyyDateConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("MM/dd/yy"));
        }
    }

    public class ShortDateConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToShortDateString());
        }
    }

typeof(ShortDateConverter) is used, and typeof(MmddyyDateConverter) is ignored here:

[JsonConverter(typeof(MmddyyDateConverter))]
public DateTime? OfferDate { get; set; }
K.S.
  • 110
  • 9
  • According to [Converter registration precedence](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#converter-registration-precedence) *a converter is chosen for each JSON element in the following order, listed from highest priority to lowest: 1) `[JsonConverter]` applied to a property. 2) A converter added to the `Converters` collection. 3) `[JsonConverter]` applied to a custom value type or POCO.* – dbc Aug 26 '20 at 03:30
  • Is this what you are currently seeing, or are you actually seeing the `[JsonConverter(typeof(MmddyyDateConverter))]` applied to a property getting ignored in preference to some other converter? – dbc Aug 26 '20 at 03:30

0 Answers0