0

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?

Nin
  • 11
  • 5
  • Configuration has it's own binder. Also configuration is not JSON, configuration is a collection of key-value pairs which can be represented as JSON. – Guru Stron Aug 08 '23 at 22:37
  • @GuruStron What modifications should I do to get the derived object in that case? – Nin Aug 08 '23 at 22:55

0 Answers0