javisrk javisrk - 2 months ago 14
C# Question

Passing a object with a list to Web API

I'm having trouble passing a list of objects via JSON to Web Api.

The method:

public HttpResponseMessage SubmitCourierRequest([FromBody]CRRequest request)
{
//code goes here
}


The CRRequest object:

public class CRRequest
{
public List<MediaItem> MediaItems = new List<MediaItem>();
public DistributionList DistributionList { get; set; }
public string SendTo { get; set; }
public string Subject { get; set; }
public string Comments { get; set; }
}


The media item class:

public abstract class MediaItem : INotifyPropertyChanged
{
[DataMember]
public virtual string ID { get; set; }

[DataMember]
public double Longitude { get; set; }

[DataMember]
public double Latitude { get; set; }

[DataMember]
public int AgencyID { get; set; }

...
}


The json I'm passing:

{
"SendTo": "bob@bob.com",
"Subject": "asda",
"Comments": "asdasd",
"ExpirationDate": "2016-11-01",
"DistributionList": {
"DistributionListID": "4"
},
"MediaItems": [{
"ID": "001"
},
{
"ID": "002"
}]
}


When I debug the method, I can get everything but the the media items, which gives me a count of 0. Am I missing something here?

Answer

Its because MediaItem is marked as abstract so it cannot be instantiated as the underlying concrete type is unknown at call time.

Do you have a concrete type you can use instead (easiest/fastest solution)? Otherwise you will have to provide a binder that can identify the correct the type based on the raw json (or something else). If you are using json.net see Deserializing JSON to abstract class.