0

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?

javisrk
  • 582
  • 4
  • 19
  • 2
    What does the `MediaItem` class look like? – Matt Rowland Oct 03 '16 at 18:40
  • @MattRowland Added class to original post. – javisrk Oct 03 '16 at 18:47
  • 4
    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 http://stackoverflow.com/q/20995865/1260204. – Igor Oct 03 '16 at 18:52
  • @Igor Doh. That was it. Danke. – javisrk Oct 03 '16 at 18:59

1 Answers1

2

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.

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175