You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[System.Text.Json] JsonConverter lacks ability to specify converter for items in a collection #54189
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.
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
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.
Reacted by Fa鸽, Maximilian Chaplin, N0D4N, Anton Egorov, Victor Irzak, Sipke Schoorstra, Mrxx99, Luigi Grilli, Sibusten, Andrew Boklashko and 16 more
You want per reference or per enum serialization behavior
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.
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>publicclassJsonCollectionItemConverter<TDatatype,TConverterType>:JsonConverter<IEnumerable<TDatatype>>whereTConverterType: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>publicoverrideIEnumerable<TDatatype>Read(refUtf8JsonReaderreader,TypetypeToConvert,JsonSerializerOptionsoptions){if(reader.TokenType==JsonTokenType.Null){returndefault(IEnumerable<TDatatype>);}JsonSerializerOptionsjsonSerializerOptions=newJsonSerializerOptions(options);jsonSerializerOptions.Converters.Clear();jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());List<TDatatype>returnValue=newList<TDatatype>();while(reader.TokenType!=JsonTokenType.EndArray){if(reader.TokenType!=JsonTokenType.StartArray){returnValue.Add((TDatatype)JsonSerializer.Deserialize(refreader,typeof(TDatatype),jsonSerializerOptions));}reader.Read();}returnreturnValue;}/// <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>publicoverridevoidWrite(Utf8JsonWriterwriter,IEnumerable<TDatatype>value,JsonSerializerOptionsoptions){if(value==null){writer.WriteNullValue();return;}JsonSerializerOptionsjsonSerializerOptions=newJsonSerializerOptions(options);jsonSerializerOptions.Converters.Clear();jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());writer.WriteStartArray();foreach(TDatatypedatainvalue){JsonSerializer.Serialize(writer,data,jsonSerializerOptions);}writer.WriteEndArray();}}
Reacted by Ultrafeel, Vladyslav Romanchuk and Brandon Dusseau
Have you tried either 1) registering your custom Saturation converter with JsonSerializerOptions.Converters or 2) adding a JsonCoverterAttribute annotation to your Saturation class?
Here is the code that works for us (we built it as a workaround). Can you check if this is working for you?
namespaceMicrosoft.Json.CustomJsonConverters{usingSystem;usingSystem.Collections.Generic;usingSystem.Text.Json;usingSystem.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>publicclassJsonCollectionItemConverter<TDatatype,TConverterType>:JsonConverter<IEnumerable<TDatatype>>whereTConverterType: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>publicoverrideIEnumerable<TDatatype>Read(refUtf8JsonReaderreader,TypetypeToConvert,JsonSerializerOptionsoptions){if(reader.TokenType==JsonTokenType.Null){returndefault(IEnumerable<TDatatype>);}JsonSerializerOptionsjsonSerializerOptions=newJsonSerializerOptions(options);jsonSerializerOptions.Converters.Clear();jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());List<TDatatype>returnValue=newList<TDatatype>();while(reader.TokenType!=JsonTokenType.EndArray){if(reader.TokenType!=JsonTokenType.StartArray){returnValue.Add((TDatatype)JsonSerializer.Deserialize(refreader,typeof(TDatatype),jsonSerializerOptions));}reader.Read();}returnreturnValue;}/// <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>publicoverridevoidWrite(Utf8JsonWriterwriter,IEnumerable<TDatatype>value,JsonSerializerOptionsoptions){if(value==null){writer.WriteNullValue();return;}JsonSerializerOptionsjsonSerializerOptions=newJsonSerializerOptions(options);jsonSerializerOptions.Converters.Clear();jsonSerializerOptions.Converters.Add(Activator.CreateInstance<TConverterType>());writer.WriteStartArray();foreach(TDatatypedatainvalue){JsonSerializer.Serialize(writer,data,jsonSerializerOptions);}writer.WriteEndArray();}}}
@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.
@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.
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!
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.
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.
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:
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.
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:
Activity
eiriktsarpalis commentedon Jun 15, 2021
Playing devil's advocate, is there anything in your scenario that prevents you from doing
or registering the converter for the enum via
JsonSerializerOptions?RamjotSingh commentedon Jun 15, 2021
There are a lot of reasons to not do this
I don't think 3 ways of specifying converter are not replacement for each other.
RamjotSingh commentedon Jun 15, 2021
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.
ericstj commentedon Jun 18, 2021
@steveharter does this get any easier with #36785?
26 remaining items
eiriktsarpalis commentedon Mar 25, 2024
Have you tried either 1) registering your custom Saturation converter with JsonSerializerOptions.Converters or 2) adding a JsonCoverterAttribute annotation to your Saturation class?
RamjotSingh commentedon Mar 26, 2024
Here is the code that works for us (we built it as a workaround). Can you check if this is working for you?
How to use?
First is the data type, second is the Converter to use for each item.
gpuchtel commentedon Mar 26, 2024
@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.
gpuchtel commentedon Mar 26, 2024
@RamjotSingh Thanks, I'll give a try...
eiriktsarpalis commentedon Mar 26, 2024
Can you share a repro?
gpuchtel commentedon Mar 26, 2024
@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.
gpuchtel commentedon Mar 27, 2024
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!
rcdailey commentedon Mar 27, 2024
Is there information I can read to understand more about what "Saturation" classes are?
gpuchtel commentedon Mar 28, 2024
@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.
rcdailey commentedon Mar 28, 2024
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.
eiriktsarpalis commentedon Mar 28, 2024
@rcdailey the workaround should look something like this:
Then serializing instances of, say,
List<MyPoco>will useMyCustomConverterfor the element types.rcdailey commentedon Mar 28, 2024
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.
eiriktsarpalis commentedon Mar 28, 2024
That's right, it's the sample class referenced in the linked SO discussion.
nhuizenga commentedon Mar 28, 2025
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.Jsonlibrary. Ignore me!Unfortunately, this doesn't appear to work if you are trying to apply the
[JsonConverter]to anEnumtype, then have that type used in a collection that is a member of another class. At least not usingSystem.Text.Jsonversion9.0.3. Here's the basic setup:If I have a custom converter that uses the
[Display]attributes to determine the string representation of the enum values, an instance ofMyDtoconstructed asnew 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 theJsonSerializerOptions.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 toJsonSerializerOptions.Converters, this deserializes just fine. Using the attribute in this scenario seems to have no effect whatsoever.Here is the converter code:
aromaa commentedon May 5, 2025
Could this be solved by adding a
TargetTypeto theJsonConverterAttribute? That way you can target multiple different types too. Now the example would look like: