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": "[email protected]",
    "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?

4
  • 2
    What does the MediaItem class look like? Commented Oct 3, 2016 at 18:40
  • @MattRowland Added class to original post. Commented Oct 3, 2016 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 stackoverflow.com/q/20995865/1260204. Commented Oct 3, 2016 at 18:52
  • @Igor Doh. That was it. Danke. Commented Oct 3, 2016 at 18:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.