0

I have an APIController that one of its methods is expecting a [FromBody] List<AbstractEntity> . AbstractEntity is an abstract class and it is implemented by let's call them ConcreteEntity1 and ConcreteEntity2. How is this setup in C# .NET so that deserialization works? In my json everything is fine but an empty list of objects is passed in the APIController method.

Here is how the method looks:

[HttpPut]
[Route("x/y/z")]
public void SomeMethod([FromBody] List<AbstractEntity> entities) { ... }

In Java Spring this is how I have set it in the past: I have a variable nodeClass in each of the concrete implementations that is being checked against so the correct class is chosen during deserialization. In abstract entity I put those annotations at the top of the class:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "nodeClass"
)

@JsonSubTypes({
    @JsonSubTypes.Type(value = ConcreteEntity1.class, name="Concrete1"),
    @JsonSubTypes.Type(value = ConcreteEntity2.class, name="Concrete2"),
})
public abstract class AbstractEntity { ... }

I am hoping there is a concise solution that doesn't involve custom deserializers..

Any help is appreciated! Thanks

dbc
  • 104,963
  • 20
  • 228
  • 340
Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106
  • 1
    Just to confirm, you are using [tag:asp.net-web-api], correct? – dbc Mar 22 '16 at 15:48
  • @dbc I assume so - My controller extends System.Web.Http.ApiController and it is a pure json in/out controller without views – Michail Michailidis Mar 22 '16 at 16:07
  • Does [Deserialising Json to derived types in Asp.Net Web API](https://stackoverflow.com/questions/12638741/deserialising-json-to-derived-types-in-asp-net-web-api) answer your question? You could also check [JsonConverter with Interface](https://stackoverflow.com/questions/33321698), [Json.Net Serialization of Type with Polymorphic Child Object](http://stackoverflow.com/questions/29528648) or [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/questions/19307752) for alternative solutions. – dbc Mar 22 '16 at 16:39
  • @dbc All those are based on custom json deserializers right? I was expecting a simpler solution/configuration.. – Michail Michailidis Mar 22 '16 at 18:00
  • 1
    In the [Deserialising Json to derived types in Asp.Net Web API](https://stackoverflow.com/questions/12638741/deserialising-json-to-derived-types-in-asp-net-web-api) question, look at the second answer that uses `TypeNameHandling.Auto` – dbc Mar 22 '16 at 18:21
  • That's awesome @dbc. Thanks! That answer is kind of buried so I didn't see it the first time. – Michail Michailidis Mar 23 '16 at 14:05

0 Answers0