0

I have a simple query and I want to map it into my DTO.

{
  "list": [
    { "propA": "A1" },
    { "propA": "A2" },
    { "propB": "B1" },
    ...
  ]
}

I tried something like this, but of course the .net couldn't figure out which class should use for map into:

public abstract class BaseClass {
}

public class ClassA : BaseClass {
  public string PropA { get; set; }
}

public class ClassB : BaseClass {
  public string PropB { get; set; }
}

public class MyDto {
  public List<BaseClass> List { get; set; }
}

Finally my controller class method for the sake of completeness:

[HttpPost]
public Task<IActionResult> Create(MyDto obj) {
  ...
}

So the question is, how can I map my JSON request body into my object with PropA and PropB properties?

KDani
  • 358
  • 4
  • 19

1 Answers1

1

Assuming you're using Json.Net to (de)serialize json, the JsonSubTypes library supports deserializing to a set of subclasses based on the presence of specific properties in each subclass:

https://github.com/manuc66/JsonSubTypes#deserializeobject-mapping-by-property-presence

In your case, you would decorate your base class with:

[JsonConverter(typeof(JsonSubtypes))]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(ClassA), "PropA")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(ClassB), "PropB")]
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
  • Maybe I'm doing something wrong, but when I iterate over the List with `.GetType()`, the result is the `BaseClass` instead of `ClassA` and `ClassB`. – KDani Mar 26 '21 at 14:45
  • Oh, I forgot to replace the default json serializer to newtonsoft's, now it works fine. – KDani Mar 26 '21 at 15:12