Valmir Cinquini
Valmir Cinquini

Reputation: 371

json array of complex object is always null on post

My project: ASP.Net Web Api, Dot.Net Core 2.0, VS 2017.

This is my model:

public class AddressData
{
    public string id { get; set; }
    public string address { get; set; }
    public int number { get; set; }
    public string complement { get; set; }
}

This is my controller

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpPost]
    public IActionResult Post([FromBody] List<AddressData> value)
    {
        if (value == null)
            return BadRequest();

        return Ok();
    }

}

This is my Json:

{
"value" : [
    {
        "id" : "08921619810",
        "address" : "ilicinia",
        "number" : 154,
        "complement": ""
    },
    {
        "id" : "12345678910",
        "address" : "candido figueiredo",
        "number" : 581,
        "complement": "ap 15"
    }
]
}

the request parameter 'value' is always NULL. If I change the controller method signature to

    [HttpPost]
    public IActionResult Post([FromBody] AddressData value)

remove and use the following Json

{
"id" : "08921619810",
"address" : "ilicinia",
"number" : 154,
"complement": ""
}

Everything works fine. If I change to [FromForm], it works, but the List of objects contains no elements (Count property = 0).

I'm using Postman, configured to send POST messages in "application/json" for content type.

Can someone tell me where I'm doing wrong?

Upvotes: 2

Views: 3310

Answers (1)

marcusturewicz
marcusturewicz

Reputation: 2494

There is a mismatch between the object you're sending in JSON, and the C# POCO object you're trying to deserialise into. The JSON you're sending is not a list of AddressData, it is an object that looks like this is C#:

using System;
using System.Collections.Generic;

namespace Yournamespace
{
    public class AddressDataList
    {
        public List<AddressData> value { get; set; }
    }

    public class AddressData
    {
        public string id { get; set; }
        public string address { get; set; }
        public int number { get; set; }
        public string complement { get; set; }
    }
}

If you change your controller to accept AddressDataList, it should now deserialize correctly:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpPost]
    public IActionResult Post([FromBody] AddressDataList addressDataList)
    {
        if (addressDataList == null)
            return BadRequest();

        return Ok();
    }

}

Upvotes: 3

Related Questions