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
Provide option for the serializer to treat IEnumerables like objects with members #1808
changed the title [-]Serializing a class that implements IEnumerable<T> with[/-][+]Serializing a class that implements IEnumerable<T> with System.Text.Json[/+]on Jan 16, 2020
I don't think so at this time. I believe if the object we are serializing at the top level is an enumerable, we ignore other top level attributes all the time.
Adding an optional parameter for this may be nice; serializing a List would probably include Count and Capacity. It also brings the question if the parameter applies to enumerable serialization at all levels or just top level (For all serialized Lists we'd get the Count and Capacity also).
The expected output you put is what I would imagine this situation done through composition.
public class MyObject
{
public int Doing { get; set; }
public IEnumerable<string> Stuff { get; set; }
}
@vitalie-ucommerce, is there any reason you couldn't wrap the IEnumerable<T> into a containing class that has the properties you want serialized as @colathro mentioned?
@ahsonkhan that would be easiest, of course. But it's not what the requirements are, we need like a IEnumerable with some meta information.
So we can use it to something like this:
var myObject = new MyObject();
foreach(var item in myObject){
...
}
Json Deserializers detect IEnumerable and expect the JSON at that level to therefore be a set (where this class represents a complex object containing both set metadata and set members). I can override that behaviour with Newtonsoft by adding the [JsonObject] attribute to the object and it does the job perfectly - and Newtonsoft's exception message gives a load of help which leads to this. I can't find a way to do the same for System.Text.Json. Also, really descriptive exception messages that guide the developer are one of my favourite things to create and see.
(Changing to an IReadOnlyCollection doesn't help, but ReadOnly IEnumerables could be a way to 'hint' that they're not meant to be deserialized into?)
I know there is a big library of junk for dealing with Amazon stuff. That is not the answer I'm looking for - it's likely to just add delay and potentially more questions. This is a working example of where this falls over.
In the immediate term, I'm likely to just create a customised collection to replace the array of dictionaries, but it would be cool if I could just convince the deserializer to fill the object.
ReadOnly IEnumerables could be a way to 'hint' that they're not meant to be deserialized into
I don't think this is enough information for the serializer to change the normal behavior.
It seems that the way to move forward here is if there were an explicit way to tell the serializer to treat an IEnumerable like an object with properties, similar to Newtonsoft's [JsonObject] attribute. I'll rename this issue to reflect this.
changed the title [-]Serializing a class that implements IEnumerable<T> with System.Text.Json[/-][+]Provide option for the serializer to treat IEnumerables like objects with members[/+]on Feb 1, 2020
Have recently bumped up against this limitation had to remove the interfaces to get our custom collections to work. Luckily foreach only requires the presence of the enumerator method.
From the looks of it, we can't disable this behaviour or even replace the enumerable converter. Further comment would be welcome.
The workaround here is to write a custom converter for the type. Here's an example using the MyEnumerable type from the issue description. This example assumes default options are used. The code can be run here.
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Text.Json;usingSystem.Text.Json.Serialization;publicclassProgram{publicstaticvoidMain(){varmy=newMyEnumerable();my.Stuff=newList<string>{"one","two"};my.Doing=3;varoptions=newJsonSerializerOptions{Converters={newMyEnumerableConverter()}};stringjson=JsonSerializer.Serialize(my,options);Console.WriteLine(json);// {"Doing":3,"Stuff":["one","two"]}my=JsonSerializer.Deserialize<MyEnumerable>(json,options);Console.WriteLine(my.Doing);// 3Console.WriteLine(my.Stuff[0]);// oneConsole.WriteLine(my.Stuff[1]);// two}publicclassMyEnumerable:IEnumerable<string>{publicintDoing{get;set;}publicIList<string>Stuff{get;set;}publicIEnumerator<string>GetEnumerator(){returnStuff.GetEnumerator();}IEnumeratorIEnumerable.GetEnumerator(){returnGetEnumerator();}}publicclassMyEnumerableConverter:JsonConverter<MyEnumerable>{publicoverrideMyEnumerableRead(refUtf8JsonReaderreader,TypetypeToConvert,JsonSerializerOptionsoptions){// By default, serializer handles null deserialization for reference types.Debug.Assert(reader.TokenType!=JsonTokenType.Null);if(reader.TokenType!=JsonTokenType.StartObject){thrownewJsonException();}varobj=newMyEnumerable();do{reader.Read();if(reader.TokenType==JsonTokenType.PropertyName){stringpropName=reader.GetString();reader.Read();if(propName=="Doing"){obj.Doing=reader.GetInt32();}elseif(propName=="Stuff"){obj.Stuff=JsonSerializer.Deserialize<IList<string>>(refreader,options);}else{reader.Skip();}}elseif(reader.TokenType==JsonTokenType.EndObject){break;}}while(true);returnobj;}publicoverridevoidWrite(Utf8JsonWriterwriter,MyEnumerablevalue,JsonSerializerOptionsoptions){// By default, serializer handles null serialization.Debug.Assert(value!=null);writer.WriteStartObject();writer.WriteNumber("Doing",value.Doing);writer.WritePropertyName("Stuff");JsonSerializer.Serialize(writer,value.Stuff,options);writer.WriteEndObject();}}}
@layomia , is the workaround temporary or permanent (as in, there are no plans to support it out of the box)? This is blocking our migration from newtonsoft as well
@rvarna - we could support this out of the box in the future. This is not planned for .NET 6.0 since there is a workaround and the community demand for this is low compared to other features.
One possible workaround is to simply expose ObjectConverterFactory. Users would then be able to to simply opt in to object semantics by applying the JsonConverter attribute. @layomia thoughts?
Activity
[-]Serializing a class that implements IEnumerable<T> with[/-][+]Serializing a class that implements IEnumerable<T> with System.Text.Json[/+]colt-1 commentedon Jan 16, 2020
I don't think so at this time. I believe if the object we are serializing at the top level is an enumerable, we ignore other top level attributes all the time.
Adding an optional parameter for this may be nice; serializing a List would probably include Count and Capacity. It also brings the question if the parameter applies to enumerable serialization at all levels or just top level (For all serialized Lists we'd get the Count and Capacity also).
The expected output you put is what I would imagine this situation done through composition.
ahsonkhan commentedon Jan 25, 2020
@vitalie-ucommerce, is there any reason you couldn't wrap the
IEnumerable<T>into a containing class that has the properties you want serialized as @colathro mentioned?vbelinschi commentedon Jan 27, 2020
@ahsonkhan that would be easiest, of course. But it's not what the requirements are, we need like a
IEnumerablewith some meta information.So we can use it to something like this:
but also like this:
layomia commentedon Feb 1, 2020
From @HughPH in #30855:
layomia commentedon Feb 1, 2020
From myself in #30855:
I'll rename this issue as well.
[-]Serializing a class that implements IEnumerable<T> with System.Text.Json[/-][+]Provide option for the serializer to treat IEnumerables like objects with members[/+]vborovikov commentedon Oct 7, 2020
Is there a workaround for this since it's not yet supported out of the box?
arjunsol commentedon Oct 21, 2020
Have recently bumped up against this limitation had to remove the interfaces to get our custom collections to work. Luckily foreach only requires the presence of the enumerator method.
From the looks of it, we can't disable this behaviour or even replace the enumerable converter. Further comment would be welcome.
layomia commentedon Oct 21, 2020
The workaround here is to write a custom converter for the type. Here's an example using the
MyEnumerabletype from the issue description. This example assumes default options are used. The code can be run here.rvarna commentedon Jan 21, 2021
@layomia , is the workaround temporary or permanent (as in, there are no plans to support it out of the box)? This is blocking our migration from newtonsoft as well
layomia commentedon Jan 21, 2021
@rvarna - we could support this out of the box in the future. This is not planned for .NET 6.0 since there is a workaround and the community demand for this is low compared to other features.
eiriktsarpalis commentedon Oct 21, 2021
One possible workaround is to simply expose
ObjectConverterFactory. Users would then be able to to simply opt in to object semantics by applying theJsonConverterattribute. @layomia thoughts?eiriktsarpalis commentedon Jan 14, 2022
Closing in favor of #63791.