2

I have the following method signature on a WebAPI endpoint:

[HttpPost]
public async Task<IHttpActionResult> AddShopping(List<ShoppingList> shoppingList)
{

This is example JSON received in the POST body:

[
    {
        "name":"Bob",
        "items":{"food":"apple","quantity":1}
    },
    {
        "name":"Tim",
        "items":[{"food":"orange","quantity":3}]
    },
    {
        "name":"John",
        "items":[
            {"food":"banana","quantity":3},
            {"drink":"coke","quantity":2}
            ]
    }
]

Notice the first 'items' is an object and the second and third 'items' are arrays.

I want to bind it to this model, so the object in the first 'items' is put into the 'Items' List. If this is possible, how do I do it? Hopefully it's a matter of decorating the 'Items' property in the model with an attribute!

namespace Test
{
    using System.Collections.Generic;

    public class ShoppingList
    {
        public List<Item> Items { get; set; }
        public string Name { get; set; }
    }

    public class Item
    {
        public string Food { get; set; }
        public int Quantity { get; set; }
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
metalhead
  • 21
  • 4
  • 7
    Nope. you would need to make a custom model binder. Are you in control of how the data is sent? that inconsistent data is only going to cause you more trouble. – Nkosi Feb 12 '17 at 04:10
  • 3
    Yes @Nkosi, I probably will be in control of how the data is sent. Someone else is designing a system to be as flexible as possible and asked me if sending a single object or an array of objects in the same JSON property was possible. I told them I suspected it would be a problem, but would look into it; and so far have come to the conclusion it's more hassle that its worth. Thanks. – metalhead Feb 12 '17 at 12:59
  • 1
    Definitely more trouble than it is worth – Nkosi Feb 12 '17 at 13:01
  • Similar question is here: http://stackoverflow.com/questions/42230008/cannot-deserialize-the-current-json-array-when-returned-value-can-be-either-arra/42230096#42230096 – Just Shadow Feb 15 '17 at 11:29

0 Answers0