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.

3

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.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật