1

My challenge is deserialize request from body to interface instance. It means any request implements that interface, but before it goes to controller action, the request should be instantioned by JsonConverter. The example request is:

  "payload":{
  "timelineEventType":"Graduation",
  "Name":"test",
  "IsGraduationPredicted":false,
  "GraduationDate":"2020-02-11T14:25:01.2310384Z",
  "QualificationId":null,
  "QualificationName":"test",
  "Grade":"5",
  "TimelineEventType":0,
  "Subjects":null

}

Model of this request is:

    public class CreateGraduationEventDto : ITimelineRequest
{ 
    public Guid? InstitutionId { get; set; }

    public string Name { get; set; }

    public bool IsGraduationPredicted { get; set; }

    public DateTime GraduationDate { get; set; }

    public Guid? QualificationId { get; set; }

    public string QualificationName { get; set; }

    public string Grade { get; set; }

    public ISet<Subject> Subjects { get; set; }

    public TimelineEventType TimelineEventType { get; set; }
}

This "payload" will be part of below model. There will be many of create timeline requests. CreateTimelineEventRequest is the body of controller action.

    public class CreateTimelineEventRequest
{
    public Guid ProfileId { get; set; }
    public Guid TimelineId { get; set; }
    public Guid IdentityId { get; set; }
    public ITimelineRequest Payload { get; set; }
}

Is there any way to instantiate ITimelineRequest in regards of body to appropriate object using eg. reflection?

Lutz Harrold
  • 123
  • 3
  • 10
  • Can't you create a request and create a payload (new CreateGraduationEventDto) and just set the Payload property of the request to the CreateGraduationEventDto instance? – Rob Sedgwick Feb 17 '20 at 17:21
  • Yes, of course I can, but I'd prefer to automatically convert JSON request to ITimelineRequest instance without knowing about type of ITimelineRequest object, because there will be many of ITimelineRequest models... I'm wondering about conversion to appropriate instance of ITimelineRequest using reflection, but I don't know how to do this... – Lutz Harrold Feb 17 '20 at 17:36
  • Please see [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182), [Json.Net Serialization of Type with Polymorphic Child Object](https://stackoverflow.com/q/29528648/3744182) or [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182). – dbc Feb 17 '20 at 20:14

0 Answers0