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
Serialization of properties from inherited interfaces vs abstract base classes #41749
public abstract class IBase
{
public string BaseProperty { get; set; }
}
public abstract class IDerived : IBase
{
public string DerivedProperty { get; set; }
}
public class Derived : IDerived
{
}
public class Data
{
public IDerived Derived { get; set; }
}
Reacted by cinderblockgames, Kenny, Sven Vinkemeier, Nathanael Frey, Sven Vinkemeier and Krzysztof Wicher
System.Text.Json uses the declared type (typeof(IDerived)) to determine what properties to serialize, and does not provide polymorphic serialization by inspecting the runtime type. See #29937 which tracks an opt-in feature to enable this behavior. The reason the abstract class example works is that we can discover the base properties from the derived type.
Also see a corresponding issue for polymorphic deserialization - #30083.
Discovering the base properties from base interfaces can be tracked individually from (but designed/implemented alongside) the polymorphic (de)serialization features. We should probably do it by default (potentially breaking as more properties may be (de)serialized), but provide an option to turn off this behavior.
This is not a regression from 3.1, so I'll set the milestone as 6.0.
It seems that System.Text.Json.JsonSerializer only serializes the properties of the top-level interface, instead of all the underlying interface. Suppose the following code:
public interface IBase
{
int Count { get; set; }
}
public interface IDerived : IBase
{
string Name { get; set; }
}
public class Implementation : IDerived
{
public int Count { get; set; }
public string Name { get; set; }
}
internal static class Program
{
private static void Main(string[] args)
{
var obj = new Implementation {Count = 1, Name = "Test"};
// {"Count":1,"Name":"Test"}
System.Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(obj));
// {"Name":"Test"} <-- Count is not serialized, because it's defined in a base interface
System.Console.WriteLine(System.Text.Json.JsonSerializer.Serialize((IDerived)obj));
}
}
When serializing the object as IDerived then only the properties that are defined in this interface are exported. I could imagine this behaviour when IDerived wasn't derived from IBase and when Implementation would derive from both base interfaces. But the properties of IDerived should include also the base properties to make sure you can serialize the object appropriately.
I am familiar that the behaviour has changed (compared to the Newtonsoft.Json serializer), but this behaviour is very unexpected and doesn't seem right. The properties of the base interface are part of IDerived and should be serialized. I couldn't think of a reason not to (de)serialize the base properties, but if it's breaking existing code, then please add a property to opt-in for base-property serialization.
Reacted by cinderblockgames, Maleaume, Kenny, Sven Vinkemeier, arashnsi13, Milica Djordjevic and Luis Taboada
When I think of it. This is just how it should be. Any type that deserializes to iderived should be sufficient. (Inherited interfaces are just runtime implementations) If you have polymorphic serialization it would be the runtime type. For which I created a polymorphic converter. Which is pretty straight forward. Please check the converter here #29937 (comment)
It's pretty unfortunate that after several years of System.Text.Json this kind of basic functionality is still not present. I have created a workaround.
I created a JsonConverter that writes out the actual underlying type:
This can be added to an interface by annotating the type with JsonConverter(typeof(JsonSerializeImplementation<...>)). But to make life a bit easier, I also added an attribute that can be applied:
Of course, just adding an attribute to a type doesn't make a real difference, so I created a JsonConverterFactory that creates the proper JsonConverter if the JsonSerializeImplementationAttribute attribute is applied to an interface.
adding properties we want at the contract level - this code has been only tested on the original code - adjust if needed:
usingSystem.Collections.Generic;usingSystem.Text.Json;usingSystem.Text.Json.Serialization.Metadata;Datadata=newData{Derived=newDerived{BaseProperty="B",DerivedProperty="D"}};JsonSerializerOptionsoptions=new(){TypeInfoResolver=newDefaultJsonTypeInfoResolver(){Modifiers={AddAllInterfacesModifier}}};Console.WriteLine(JsonSerializer.Serialize(data,options));// {"Derived":{"DerivedProperty":"D","BaseProperty":"B"}}staticvoidAddAllInterfacesModifier(JsonTypeInfotypeInfo){if(typeInfo.Kind!=JsonTypeInfoKind.Object)return;if(typeInfo.Type.IsInterface){Type[]interfaces=typeInfo.Type.GetInterfaces();if(interfaces.Length==0)return;Dictionary<string,JsonPropertyInfo>properties=new();foreach(varpropintypeInfo.Properties){properties.Add(prop.Name,prop);}foreach(varinterintypeInfo.Type.GetInterfaces()){varinterTypeInfo=typeInfo.Options.GetTypeInfo(inter);foreach(varpropininterTypeInfo.Properties){JsonPropertyInfopropUnderNewTypeInfo=CopyProperty(prop,typeInfo);if(properties.TryAdd(prop.Name,propUnderNewTypeInfo)){// we don't want to add duplicate names heretypeInfo.Properties.Add(propUnderNewTypeInfo);}}}}}staticJsonPropertyInfoCopyProperty(JsonPropertyInfoproperty,JsonTypeInfonewTypeInfo){JsonPropertyInfocopy=newTypeInfo.CreateJsonPropertyInfo(property.PropertyType,property.Name);copy.AttributeProvider=property.AttributeProvider;copy.Order=property.Order;copy.Set=property.Set;copy.Get=property.Get;copy.CustomConverter=property.CustomConverter;copy.IsExtensionData=property.IsExtensionData;copy.IsRequired=property.IsRequired;copy.NumberHandling=property.NumberHandling;copy.ShouldSerialize=property.ShouldSerialize;returncopy;}publicinterfaceIBase{stringBaseProperty{get;set;}}publicinterfaceIDerived:IBase{stringDerivedProperty{get;set;}}publicclassDerived:IDerived{publicstringBaseProperty{get;set;}publicstringDerivedProperty{get;set;}}publicclassData{publicIDerivedDerived{get;set;}}
I guess .Net offers pretty much solutions to serialize interfaces the way you expect them to. I don't think the framework needs to provide default converters for it. How about explicit property implementations? Keep them? Thats something the class decides, not the interface. So you can't tell for sure. How about overlapping properties? Just to name some possible issues. JTS7 offers quite perfect solutions to customize (interface) serialization your way. By the way: a big thank you to the team for this nice lib.
How about explicit property implementations? Keep them? Thats something the class decides, not the interface.
Note that this issue concerns contracts of interface types, not classes. Using the example given in the OP, the change would impact the serialization contract of values serialized as IDerived, but would have no effect if the same value gets serialized as Derived. From the perspective of an interface hierarchy, there is no such thing as an explicit implementation.
ghost locked as resolved and limited conversation to collaborators on Dec 25, 2022
Activity
Dotnet-GitSync-Bot commentedon Sep 2, 2020
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
layomia commentedon Sep 4, 2020
System.Text.Json uses the declared type (
typeof(IDerived)) to determine what properties to serialize, and does not provide polymorphic serialization by inspecting the runtime type. See #29937 which tracks an opt-in feature to enable this behavior. The reason the abstract class example works is that we can discover the base properties from the derived type.Also see a corresponding issue for polymorphic deserialization - #30083.
qsdfplkj commentedon Sep 4, 2020
It is not about the runtime type. Why does it not discover the base properties from the base interface.
layomia commentedon Sep 8, 2020
Discovering the base properties from base interfaces can be tracked individually from (but designed/implemented alongside) the polymorphic (de)serialization features. We should probably do it by default (potentially breaking as more properties may be (de)serialized), but provide an option to turn off this behavior.
This is not a regression from 3.1, so I'll set the milestone as 6.0.
layomia commentedon Feb 2, 2021
From @ramondeklein in #47753:
shaggygi commentedon May 30, 2021
Anybody know which preview this feature will start to light up in? Just curious.
qsdfplkj commentedon May 30, 2021
When I think of it. This is just how it should be. Any type that deserializes to iderived should be sufficient. (Inherited interfaces are just runtime implementations) If you have polymorphic serialization it would be the runtime type. For which I created a polymorphic converter. Which is pretty straight forward. Please check the converter here #29937 (comment)
18 remaining items
ramondeklein commentedon Nov 22, 2022
It's pretty unfortunate that after several years of
System.Text.Jsonthis kind of basic functionality is still not present. I have created a workaround.I created a
JsonConverterthat writes out the actual underlying type:This can be added to an interface by annotating the type with
JsonConverter(typeof(JsonSerializeImplementation<...>)). But to make life a bit easier, I also added an attribute that can be applied:Of course, just adding an attribute to a type doesn't make a real difference, so I created a
JsonConverterFactorythat creates the properJsonConverterif theJsonSerializeImplementationAttributeattribute is applied to an interface.All you need to do is to register this factory using
services.AddTransient<JsonConverter,JsonSerializeImplementationConverter>().There are some severe drawbacks to this solution:
krwq commentedon Nov 23, 2022
There exist simple way to workaround this scenario currently (more accurate one is further below):
and slightly more elaborate one:
eiriktsarpalis commentedon Nov 23, 2022
Let's keep this in 8.0.0 since it's being requested by a partner team.
angelaki commentedon Nov 24, 2022
I guess .Net offers pretty much solutions to serialize interfaces the way you expect them to. I don't think the framework needs to provide default converters for it. How about explicit property implementations? Keep them? Thats something the class decides, not the interface. So you can't tell for sure. How about overlapping properties? Just to name some possible issues. JTS7 offers quite perfect solutions to customize (interface) serialization your way. By the way: a big thank you to the team for this nice lib.
eiriktsarpalis commentedon Nov 25, 2022
Note that this issue concerns contracts of interface types, not classes. Using the example given in the OP, the change would impact the serialization contract of values serialized as
IDerived, but would have no effect if the same value gets serialized asDerived. From the perspective of an interface hierarchy, there is no such thing as an explicit implementation.