mercredi 9 juin 2021

Is it possible in C# to deserialize json so that a field in the json instantiates a particular subclass that has overridden functions?

Let's say you have the following portion of json:

{ "Behavior": "BehaviorTypeA" }

When you deserialize json, the deserializer will essentially import the data from the json text to a class definition, which could be like:

public class MyClass
{
    public string Behavior { get; set; }
}

But let's say that you wanted that data to indicate some kind of behavior, so perhaps your class definition might instead be

public class MyClass
{
    public BaseBehavior Behavior { get; set; }
}

Where you also have the definitions

public class BaseBehavior
{
    public abstract void DoIt();
}

And

public class BehaviorTypeA : BaseBehavior
{
    public override void DoIt()
    {
        // some functionality
    }
}

Is this possible with json deserialization, and if so, what would the json have to be and how would it be done? Might it possibly require a custom deserializer and possibly added reflection code? (The BaseBehavior class doesn't have to be abstract and might contain member fields.)





Aucun commentaire:

Enregistrer un commentaire