0

I need to convert a json string to an object of type FullArticle; the ArticleBody (property in FullArticle class) is an abstract class.

How can I deserialize it into a concrete class? I know already is HtmlBody implemented ArticleBody.

public class FullArticle : ArticleListItem
{
    public string ShortDescription { get; set; }

    // ToDo Check this for removal
    public bool IsDone { get; private set; }

    public ArticleBody Body { get; }

    public long ViewCount { get; }
    public string Keywords { get; }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • you can map it to a DTO containing only the properties you want, plus its not recommended to cast your public domain models through public APIs my best thought on this is yo create a DTO – IbraHim M. Nada Mar 21 '21 at 07:13
  • 1
    Assuming you want **always** `ArticleBody` to be deserialized as `HtmlBody`, create `ArticleBodyConverter` as a subclass of [`CustomCreationConverter`](https://www.newtonsoft.com/json/help/html/DeserializeCustomCreationConverter.htm) and override `public override ArticleBody Create(Type objectType) => new HtmlBody()` as shown in [this answer](https://stackoverflow.com/a/11761508/3744182) to [NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable](https://stackoverflow.com/q/11754633/3744182). In fact I think this is a duplicate, agree? – dbc Mar 21 '21 at 13:32
  • If not a duplicate please [edit] your question to share a [mcve] that includes (possibly simplified) versions of JSON, `ArticleBody` and `HtmlBody` that demonstrate the problem. – dbc Mar 21 '21 at 13:33
  • Or if your `ArticleBody` might actually be polymorphic, see [How to call JsonConvert.DeserializeObject and disable a JsonConverter applied to a base type via `[JsonConverter]`?](https://stackoverflow.com/q/45547123/3744182) and [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182). We need to see a [mcve] to be sure one way or the other. – dbc Mar 22 '21 at 16:49

0 Answers0