简体   繁体   中英

How to map a list of derived classes to DTO?

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?

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")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM