Polymorphic deserialization not working when deserializing appsettings.json

138 Views Asked by At

I have a base class Target and two derived classes TargetA and TargetB. From appsettings.json , I want to deserialize to the type of derived object (which can be either TargetA or TargetB at runtime).I'm using Polymorphic deserialization available in Dot Net Core 7.0, and trying to deserialize from web API project.

'''

using System.Text.Json.Serialization;

[JsonDerivedType(derivedType:typeof(TargetA), typeDiscriminator: "A")]
[JsonDerivedType(derivedType: typeof(TargetB), typeDiscriminator: "B")]
public class Target
{
  public string Prop1{get;set;}
}

public class TargetA:Target
{
  public string PropA{get;set;}
}

public class TargetB:Target
{
  public string PropB{get;set;}
}

appsettings.json
{
 "TestTarget":{
  "$type":"A",
  "PropA":"valueA",
  "Prop1":"value1"
  }

public class Program.cs
{
  ....
  var configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();
  var targetObj = configuration
                      .GetSection("TestTarget")
                      .Get<Target>();
}

'''

When running, targetObj is having only the properties of base class "Target" and not the derived class "TargetA".

To verify if I implemented JsonDerivedAttribute properly, I used below code which is picking the correct "targetA" type.

'''

var targetObj2 = new TargetA()
{
 PropA = "valueA",
 Prop1 = "value1"
}
var ser = JsonSerializer.Serialize<Target>(src);
var deser = JsonSerializer.Deserialize<Target>(ser);

'''

I'm not understanding what is missing while deserializing using "configuration.GetSection("TestTarget").Get<Target>()". Do I have to explicitly mention somewhere else?

0

There are 0 best solutions below