Search code examples
c#jsonsystem.text.json

System.Text.Json Deserialize nested Polymorphic object without type discriminator


Assume the below model:

    public enum TypeAModels
    {
       A = 1,
       B = 2
    }

   [JsonDerivedType(typeof(TypeA_A), "aa")]
   [JsonDerivedType(typeof(TypeA_B), "ab")]

    public abstract class TypeA
    {
        public abstract TypeAModels TypeAModels { get; }
    }
    public class TypeA_A : TypeA
    {
        public int Age { get; set; }
    
        public TypeB TypeB { get; set; }
        public override TypeAModels TypeAModels => TypeAModels.A;
    }
    
    public class TypeA_B : TypeA
    {
        public string Name { get; set; }
        public override TypeAModels TypeAModels => TypeAModels.B;
    }
    
    public enum TypeBModels
    {
        A = 1,
        B = 2
    }
    
    [JsonDerivedType(typeof(TypeB_A), "ba")]
    [JsonDerivedType(typeof(TypeB_B), "bb")]
    public abstract class TypeB
    {
        public abstract TypeBModels TypeBModels { get; }
    }
    public class TypeB_A : TypeB
    {
        public int Year { get; set; }
        public override TypeBModels TypeBModels => TypeBModels.A;
    }
    
    public class TypeB_B : TypeB
    {
        public string UserName { get; set; }
        public override TypeBModels TypeBModels => TypeBModels.B;
    }

//create a TypeA object of type TypeA_A
TypeA typeAA = new TypeA_A() { Age = 30, TypeB = new TypeB_A { Year = 1982 } };

var jsonString = JsonSerializer.Serialize(typeAA, new JsonSerializerOptions());

/*{
    "$type":"aa",
    "Age":30,
    "TypeB":{"$type":"ba",
             "Year":1982,
             "TypeBModels":1},
    "TypeAModels":1}*/

var deserializedTypeAA = JsonSerializer.Deserialize<TypeA>(jsonString, new JsonSerializerOptions());

When I run the JsonSerializer.Serialize code, I get the expected JSON, and when I run the JsonSerializer.Deserialize<TypeA> code it also manages to create the right object from the JSON.

The problem begins when I have a MinimalApi endpoint like:

app.MapPost("/", async (TypeA typeA).

Since the client requests are based on the model, which doesn't contain the type discriminator required for the JSON serialization to know how to deserialize it. For example, the client JSON might look like this:

{
  "Age": 30,
  "TypeB": {
    "Year": 1982,
    "TypeBModels": 1
   },
  "TypeAModels": 1
}

For such requests, the JSON serialization fails with a generic exception: System.NotSupportedException: 'Deserialization of types without a parameterless constructor, a singular parameterized...

The only way I can think of is to read and parse 'manually' each JSON field separately. It is possible but it's not an ideal way IMO. Is there a more elegant way?

Note: I found this API Proposal which might be a good solution when it is implemented, but currently it isn't implemented yet.


Solution

  • As long as your derived types are not sealed, you can apply [JsonDerivedType(typeof(TSelf))] to them to cause System.Text.Json to emit a self-identifier when serialized. Thus if I modify your models e.g. as follows:

    public enum TypeAModels
    {
       A = 1,
       B = 2
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeA_A), (int)TypeAModels.A)]
    [JsonDerivedType(typeof(TypeA_B), (int)TypeAModels.B)]
    public abstract class TypeA
    {
        protected const string MyTypeDiscriminatorPropertyName = "TypeAModels";
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeA_A), (int)TypeAModels.A)] // Self identifier
    public class TypeA_A : TypeA
    {
        public int Age { get; set; }
        public TypeB TypeB { get; set; }
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeA_B), (int)TypeAModels.B)] // Self identifier
    public class TypeA_B : TypeA
    {
        public string Name { get; set; }
    }
    
    public enum TypeBModels
    {
        A = 1,
        B = 2
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeB_A), (int)TypeBModels.A)]
    [JsonDerivedType(typeof(TypeB_B), (int)TypeBModels.B)]
    public abstract class TypeB
    {
        protected const string MyTypeDiscriminatorPropertyName = "TypeBModels";
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeB_A), (int)TypeBModels.A)] // Self identifier
    public class TypeB_A : TypeB
    {
        public int Year { get; set; }
    }
    
    [JsonPolymorphic(TypeDiscriminatorPropertyName = MyTypeDiscriminatorPropertyName)]  
    [JsonDerivedType(typeof(TypeB_B), (int)TypeBModels.B)] // Self identifier
    public class TypeB_B : TypeB
    {
        public string UserName { get; set; }
    }
    

    I can now serialize an instance of TypeA_A and deserialize as TypeA:

    TypeA_A typeAA = new() { Age = 30, TypeB = new TypeB_A { Year = 1982 } };
    
    var json = JsonSerializer.Serialize(typeAA, options);
    
    var typeABack = JsonSerializer.Deserialize<TypeA>(json);
    

    Notes:

    1. I eliminated your TypeAModels and TypeBModels properties in favor of using JsonPolymorphicAttribute.TypeDiscriminatorPropertyName. This prevents the duplication of type information in the serialized JSON but does require the type discriminator to appear first in the JSON:

      {
        "TypeAModels": 1,   // This must be the first property    
        "Age": 30,
        "TypeB": {
          "TypeBModels": 1,   // This must be the first property    
          "Year": 1982
        }
      }
      
    2. Microsoft refuses to allow type discriminator information to be emitted when serializing a sealed type. See System.Text.Json Polymorphic Type Resolving Issue #77532 which was closed by MSFT as "answered", and [API Proposal]: System.Text.Json Polymorphic Attribute Should Provide an Option to Include Type Discriminators on Derived Types #93471 which was opened specifically to enable type information to be serialized for sealed derived types.

      If your derived types are sealed, you may need to adopt an entirely different strategy, such as using a manual converter like one of ones from Is polymorphic deserialization possible in System.Text.Json?, or rewriting your endpoint to explicitly serialize using the base type rather than the concrete type.

    3. If you don't want to manually apply polymorphism options to derived types, you could create a custom typeinfo modifier to copy polymorphism options from base type contracts to derived type contracts. See e.g. this answer by Guru Stron to How can I serialize a multi-level polymorphic type hierarchy with System.Text.Json in .NET 7? for one example. It might need to be enhanced, e.g. to copy the type discriminator name.

    Demo fiddle here.