0

I am new to webapi and I am stuck with deserializing the json to the respective Child model

This is my model structure:

public abstract class FiscalInformation
{
    int amount { get; set; }
    int vat { get; set; }
}

public class GermanFiscal : FiscalInformation
{
    string germancity { get; set; }``
    string germanspecs { get; set; }
}

public class FrenchFiscal : FiscalInformation
{
    string frenchcity { get; set; }
    string frenchspecs { get; set; }
}

and this is my webapi controller:

[HttpPost]
[Route("api/fiscalinformation")]
public IHttpActionResult fiscalinformationupdate([FromBody]  FiscalInformation fiscalInformation)
{
    //fiscal information can be of type germanfiscal or of frenchfiscalinformation 
    //do something with the respective  child model
    return Ok();
}

if it is going to be a single property inside the model then i would have added

 [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]

and I dont want to setup TypeNameHandling at global level too..

whenever the child object is posted from angular the fiscalinformation object comes as null

Please help me..

melya
  • 578
  • 5
  • 24
Kannan
  • 1
  • 4
  • You would need to create a custom model binder for this to work. Otherwise the framework by default wont know what model type to initialize and bind. I would suggest you reconsider your current design choice. – Nkosi Dec 11 '17 at 17:29
  • You could apply a `JsonConverter` directly to `FiscalInformation` with `[JsonConverter(typeof(FiscalInformationConverter))]` that senses the correct subtype, along the lines of [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182). You will need to disable the converter on derived types though, as shown in [How to call JsonConvert.DeserializeObject and disable a JsonConverter applied to a base type via `[JsonConverter]`?](https://stackoverflow.com/q/45547123/3744182). – dbc Dec 11 '17 at 19:12
  • @dbc creating a custom model binder will work, but all i want is a type to be mentioned during serialisation such as { "$type": "FleetBox.Web.Areas.Api.Models.BelgianVehicleFiscalInformation, FleetBox.Web", "CountryCode": "BE" } so that the deserializer will automatically understand to which object it should be binded. something like [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)] which can be used on top of a class – Kannan Dec 12 '17 at 06:43
  • That can cause security hazards. `$type` information should be sanitized for safety. See [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954) for details. – dbc Dec 12 '17 at 06:46
  • 1
    thanks dbc.. that was a great example .. I will create a custom converter – Kannan Dec 12 '17 at 11:49

0 Answers0