Skip to content

[System.Text.Json] JsonConverter lacks ability to specify converter for items in a collection #54189

Open

Description

@RamjotSingh

JsonConverter allows specifying the conveter to be used for a specific property, however if a collection is in use and you want to use the converter to serialize a items in collection it doesn't work.

Example

public enum Day
{
   Sunday,
   Monday,
}

public class Model
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public IEnumerable<Day> Days { get; set; }
}

The above code will throw. The only way to work around is to write a custom converter which understands collections and uses a different converter for each item in collection.

I propose a new attribute which allows the caller to specify converter to use for items in collection should be added. Something like

[JsonCollectionItemConverter(typeof(JsonStringEnumConverter))]

Newtonsoft.Json allows this by allowing specifying the type in JsonProperty attribute. That option has it's own shortcomings as well. I believe the above option will solve that too.

Activity

  1. ghost added
    untriaged
    on Jun 14, 2021
  2. eiriktsarpalis commented on Jun 15, 2021

    @eiriktsarpalis
    Member

    Playing devil's advocate, is there anything in your scenario that prevents you from doing

    [JsonConverter(typeof(JsonStringEnumConverter))]
    public enum Day
    {
       Sunday,
       Monday,
    }

    or registering the converter for the enum via JsonSerializerOptions?

  3. RamjotSingh commented on Jun 15, 2021

    @RamjotSingh
    MemberAuthor

    There are a lot of reasons to not do this

    1. You want per reference or per enum serialization behavior
    2. From reading code perspective, it is easier to understand things if the converter is directly on the property itself since rest of the info (JsonPropertyName).

    I don't think 3 ways of specifying converter are not replacement for each other.

  4. RamjotSingh commented on Jun 15, 2021

    @RamjotSingh
    MemberAuthor

    If someone else hits this same problem. Here is a workaround. Its not the sanest solution hence I would like the library to support it out of the box.

         /// <summary>
        /// Json collection converter.
        /// </summary>
        /// <typeparam name="TDatatype">Type of item to convert.</typeparam>
        /// <typeparam name="TConverterType">Converter to use for individual items.</typeparam>
        public class JsonCollectionItemConverter<TDatatype, TConverterType> : JsonConverter<IEnumerable<TDatatype>>
            where TConverterType : JsonConverter
        {
            /// <summary>
            /// Reads a json string and deserializes it into an object.
            /// </summary>
            /// <param name="reader">Json reader.</param>
            /// <param name="typeToConvert">Type to convert.</param>
            /// <param name="options">Serializer options.</param>
            /// <returns>Created object.</returns>
            public override IEnumerable<TDatatype> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.Null)
                {
                    return default(IEnumerable<TDatatype>);
                }
    
                JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(options);
                jsonSerializerOptions.Converters.Clear();
                jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());
    
                List<TDatatype> returnValue = new List<TDatatype>();
    
                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    if (reader.TokenType != JsonTokenType.StartArray)
                    {
                        returnValue.Add((TDatatype)JsonSerializer.Deserialize(ref reader, typeof(TDatatype), jsonSerializerOptions));
                    }
    
                    reader.Read();
                }
    
                return returnValue;
            }
    
            /// <summary>
            /// Writes a json string.
            /// </summary>
            /// <param name="writer">Json writer.</param>
            /// <param name="value">Value to write.</param>
            /// <param name="options">Serializer options.</param>
            public override void Write(Utf8JsonWriter writer, IEnumerable<TDatatype> value, JsonSerializerOptions options)
            {
                if (value == null)
                {
                    writer.WriteNullValue();
                    return;
                }
    
                JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(options);
                jsonSerializerOptions.Converters.Clear();
                jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());
    
                writer.WriteStartArray();
    
                foreach (TDatatype data in value)
                {
                    JsonSerializer.Serialize(writer, data, jsonSerializerOptions);
                }
    
                writer.WriteEndArray();
            }
        }
  5. added
    api-suggestion
    api-needs-work
    and removed
    untriaged
    on Jun 15, 2021
  6. added this to the 7.0.0 milestone on Jun 15, 2021
  7. ericstj commented on Jun 18, 2021

    @ericstj
    Member

    @steveharter does this get any easier with #36785?

  8. removed
    api-suggestion
    on Jun 25, 2021
  9. added
    User Story
    on Jan 9, 2022
  10. added
    Priority:3
    on Feb 7, 2022
  11. 26 remaining items

  12. eiriktsarpalis commented on Mar 25, 2024

    @eiriktsarpalis
    Member

    Have you tried either 1) registering your custom Saturation converter with JsonSerializerOptions.Converters or 2) adding a JsonCoverterAttribute annotation to your Saturation class?

  13. RamjotSingh commented on Mar 26, 2024

    @RamjotSingh
    MemberAuthor

    Here is the code that works for us (we built it as a workaround). Can you check if this is working for you?

    namespace Microsoft.Json.CustomJsonConverters
    {
        using System;
        using System.Collections.Generic;
        using System.Text.Json;
        using System.Text.Json.Serialization;
    
        /// <summary>
        /// Json collection converter.
        /// </summary>
        /// <typeparam name="TDatatype">Type of item to convert.</typeparam>
        /// <typeparam name="TConverterType">Converter to use for individual items.</typeparam>
        public class JsonCollectionItemConverter<TDatatype, TConverterType> : JsonConverter<IEnumerable<TDatatype>>
            where TConverterType : JsonConverter
        {
            /// <summary>
            /// Reads a json string and deserializes it into an object.
            /// </summary>
            /// <param name="reader">Json reader.</param>
            /// <param name="typeToConvert">Type to convert.</param>
            /// <param name="options">Serializer options.</param>
            /// <returns>Created object.</returns>
            public override IEnumerable<TDatatype> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                if (reader.TokenType == JsonTokenType.Null)
                {
                    return default(IEnumerable<TDatatype>);
                }
    
                JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(options);
                jsonSerializerOptions.Converters.Clear();
                jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());
    
                List<TDatatype> returnValue = new List<TDatatype>();
    
                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    if (reader.TokenType != JsonTokenType.StartArray)
                    {
                        returnValue.Add((TDatatype)JsonSerializer.Deserialize(ref reader, typeof(TDatatype), jsonSerializerOptions));
                    }
    
                    reader.Read();
                }
    
                return returnValue;
            }
    
            /// <summary>
            /// Writes a json string.
            /// </summary>
            /// <param name="writer">Json writer.</param>
            /// <param name="value">Value to write.</param>
            /// <param name="options">Serializer options.</param>
            public override void Write(Utf8JsonWriter writer, IEnumerable<TDatatype> value, JsonSerializerOptions options)
            {
                if (value == null)
                {
                    writer.WriteNullValue();
                    return;
                }
    
                JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(options);
                jsonSerializerOptions.Converters.Clear();
                jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());
    
                writer.WriteStartArray();
    
                foreach (TDatatype data in value)
                {
                    JsonSerializer.Serialize(writer, data, jsonSerializerOptions);
                }
    
                writer.WriteEndArray();
            }
        }
    }

    How to use?

    [JsonPropertyName("changeTypes")]
    [System.Text.Json.Serialization.JsonConverter(typeof(JsonCollectionItemConverter<ResourceChangeType, JsonStringEnumConverter>))]
    public IEnumerable<ResourceChangeType> ChangeTypes { get; set; }

    First is the data type, second is the Converter to use for each item.

  14. gpuchtel commented on Mar 26, 2024

    @gpuchtel

    @eiriktsarpalis "Have you tried either 1) registering your custom Saturation converter with JsonSerializerOptions.Converters or 2) adding a JsonCoverterAttribute annotation to your Saturation class?"

    Answer(s), yes to #2 (did not work), no to #1 as I don't have control over the options, as its the Cosmos Client doing the (de)serialization

    **** UPDATE ****

    Yes, adding a JsonConverterAttribute to the class annotation worked! Sorry, I misread it at first, as I was thinking of the Dictionary annotation.

  15. gpuchtel commented on Mar 26, 2024

    @gpuchtel

    @RamjotSingh Thanks, I'll give a try...

  16. eiriktsarpalis commented on Mar 26, 2024

    @eiriktsarpalis
    Member

    yes to #2 (did not work)

    Can you share a repro?

  17. gpuchtel commented on Mar 26, 2024

    @gpuchtel

    @eiriktsarpalis Yes, it did work! I gave an 'update' above. Thanks for sticking with this. I think I'm good. Actually, this works better than the NewtonSoft solution, because it places the conversion (attribute) declaration where the Type is declared, rather than where it is used.

  18. gpuchtel commented on Mar 27, 2024

    @gpuchtel

    After much ado, Eirik Tsarpalis (Microsoft) had the answer all along; I wasn't reading it right. Adding a JsonCoverterAttribute annotation to my custom class (Saturation) works! This is better than annotating the point of usage via Newtsonsoft's JsonPropertyAttribute.ItemConverterType—it places the declaration with the class. Thank you, Eirik!

  19. rcdailey commented on Mar 27, 2024

    @rcdailey

    Is there information I can read to understand more about what "Saturation" classes are?

  20. gpuchtel commented on Mar 28, 2024

    @gpuchtel

    @rcdailey The 'Saturation' class is a custom class in my solution. I copied the code verbatim as the type of class is irrelevant to the discussion.

  21. rcdailey commented on Mar 28, 2024

    @rcdailey

    It's relevant insofar as it is part of a proposed solution or workaround, so again I'd appreciate an answer to my question as I feel it is important information for the complete understanding of the solutions discussed here.

  22. eiriktsarpalis commented on Mar 28, 2024

    @eiriktsarpalis
    Member

    @rcdailey the workaround should look something like this:

    [JsonConverter(typeof(MyCustomConverter))]
    public class MyPoco { }

    Then serializing instances of, say, List<MyPoco> will use MyCustomConverter for the element types.

  23. rcdailey commented on Mar 28, 2024

    @rcdailey

    Thanks Eirik. So the term "Saturation" was actually referring to a custom JSON converter class? If not, what is that referring to? It's not a term I've heard of in the context of System.Text.Json.

  24. eiriktsarpalis commented on Mar 28, 2024

    @eiriktsarpalis
    Member

    That's right, it's the sample class referenced in the linked SO discussion.

  25. nhuizenga commented on Mar 28, 2025

    @nhuizenga

    Update: Argh. My bad, this behavior seems to be isolated to responses in ASP.NET Core. When I wrote tests in hopes of providing a full copy/paste-able repro, the "bad" behavior went away. I'm not totally sure what's going on, but the problem seems to be outside the System.Text.Json library. Ignore me!

    [JsonConverter(typeof(MyCustomConverter))]
    public class MyPoco { }
    Then serializing instances of, say, List<MyPoco> will use MyCustomConverter for the element types.

    Unfortunately, this doesn't appear to work if you are trying to apply the [JsonConverter] to an Enum type, then have that type used in a collection that is a member of another class. At least not using System.Text.Json version 9.0.3. Here's the basic setup:

    [JsonConverter(typeof(MyEnumConverter))]
    public enum MyEnum {
      [Display(Name = "a")]
      Value1,
      [Display(Name = "b")]
      Value2,
      [Display(Name = "c")]
      Value3
    }
    public record MyDto(
      IEnumerable<MyEnum> Options,
      MyEnum DefaultOption
    );

    If I have a custom converter that uses the [Display] attributes to determine the string representation of the enum values, an instance of MyDto constructed as new MyDto([MyEnum.Value1,MyEnum.Value2], MyEnum.Value1) will, in the absence of any other configuration, serialize to {"Options":[1,2],"DefaultOption":1} even though it should be {"Options":["a","b"],"DefaultOption":"a"} (implementation below). The behavior does not change whether the converter is added to the JsonSerializerOptions.Converters, set using the attribute, or both.

    Interestingly enough, this all works much better on the deserialization side of things, though not perfectly. If you have {"Options":["a","b"],"DefaultOption":"a"} and add the custom converter to JsonSerializerOptions.Converters, this deserializes just fine. Using the attribute in this scenario seems to have no effect whatsoever.

    Here is the converter code:

    public class JsonNameEnumConverter : JsonConverter<MyEnum> {
    
        private static Dictionary<string, MyEnum> NameValueMap { get; } = typeof(MyEnum)
            .GetFields(BindingFlags.Public | BindingFlags.Static)
            .Select(m => KeyValuePair.Create(m.GetCustomAttribute<DisplayAttribute>()?.Name ?? m.Name, Enum.Parse<MyEnum>(m.Name)))
            .ToDictionary();
    
        private static Dictionary<MyEnum, string> ValueNameMap { get; } = typeof(MyEnum)
            .GetFields(BindingFlags.Public | BindingFlags.Static)
            .Select(m => KeyValuePair.Create(Enum.Parse<MyEnum>(m.Name), m.GetCustomAttribute<DisplayAttribute>()?.Name ?? m.Name))
            .ToDictionary();
    
        public override MyEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
            NameValueMap[reader.GetString() ?? string.Empty];
    
        public override void Write(Utf8JsonWriter writer, MyEnum value, JsonSerializerOptions options) =>
            writer.WriteStringValue(ValueNameMap[value]);
    }
  26. aromaa commented on May 5, 2025

    @aromaa
    Contributor

    Could this be solved by adding a TargetType to the JsonConverterAttribute? That way you can target multiple different types too. Now the example would look like:

    public class Model
    {
        [JsonConverter(typeof(JsonStringEnumConverter), TargetType = typeof(Day))]
        public IEnumerable<Day> Days { get; set; }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Team:LibrariesUser Storyapi-needs-workarea-System.Text.Jsonpartner-impact

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions