Mohsin Mushtaq
Mohsin Mushtaq

Reputation: 119

How to deserialize json array data in ASP.NET MVC controller

I had successfully deserialized a simple json object but when I send an array of json object using a POST request to my controller, it fails. Here is my code:

[HttpPost]
public string addWwarehouse([FromBody] warehouse warehouses)
{
      System.Diagnostics.Debug.WriteLine(warehouses[0].name);
      return "success";
}

This is working json data:

{
    "warehouses":
    {
        "name":"WarehouseA",
        "location":"locationA"
    }
}

But when I use an array like this,

[{
    "warehouses":
    {
        "name":"WarehouseA",
        "location":"locationA"
    }
}]

It doesn't work. I also tried using List<warehouse> but still no luck. This is my warehouse class:

public class warehouse { 
    public string name  { get; set; }
    public string location { get; set; }
}

Upvotes: 1

Views: 1619

Answers (2)

Fabjan
Fabjan

Reputation: 13676

Welcome to StackOverflow.

It doesn't because your model is not a List<warehouse>:

[{
    "warehouses":
    {
        "name":"WarehouseA",
        "location":"locationA"
    }
}]

It is an array of objects each with a property called "warehouses" that contains a singular object of type warehouse. You might want to send an array of warehouses instead:

[{
    "name":"WarehouseA",
    "location":"locationA"
}, {
    "name":"WarehouseB",
    "location":"locationB"
}]

And deserialize it to List<warehouse>

P.S. If you have no control over json format then the answer by @Tiago Ávila should do the trick.

Let's inspect the model:

[{                                // [...] - array of some outer objs
    "warehouses":                 // with single property
    {                
        "name":"WarehouseA",      // inner obj that resides inside outer obj
        "location":"locationA"
    }
}]

Upvotes: 2

Tiago &#193;vila
Tiago &#193;vila

Reputation: 2867

Because the way that your json is, you need a class like this:

public class Warehouses
{
    public string name { get; set; }
    public string location { get; set; }
}

public class RootObject
{
    public Warehouses warehouses { get; set; }
}

Then, in your action shoud be like this:

public string addWwarehouse([FromBody] RootObject warehouses)

I think this will resolve.

Upvotes: 2

Related Questions