1

I have the following json data which i used in RestClient to post.

{
  "Cars": [
      {
        "color":"Blue",
        "miles":100,
        "vin":"1234"
      },
      {
        "color":"Red",
        "miles":400,
        "vin":"1235"
      }
  ],
  "truck": {
    "color":"Red",
    "miles":400,
    "vin":"1235"
  }
}

and i am trying to get this json in a single object at server side while do post from Rest Client

public JsonResult Post([FromBody]Object Cars)
{
    return Cars;
}

How can i get this json in a single object?

dan richardson
  • 3,871
  • 4
  • 31
  • 38

2 Answers2

0

If you need the entire JSON into an object then here I used json2csharp.com to convert your JSON into classes.

public class Car
{
    public string color { get; set; }
    public int miles { get; set; }
    public string vin { get; set; }
}

public class Truck
{
    public string color { get; set; }
    public int miles { get; set; }
    public string vin { get; set; }
}

public class RootObject
{
    public List<Car> Cars { get; set; }
    public Truck truck { get; set; }
}

Change your API to:

public JsonResult Post([FromBody]RootObject root)
{
    return root.Cars; // List<Car>
}

Now you can access Cars and truck.

jegtugado
  • 5,081
  • 1
  • 12
  • 35
-1

This has been asked many times before: Posting array of objects with MVC Web API

You may be better using a class to represent the object

public class Vehicle
{
    public string color;
    public string type;
    public int miles;
    public int vin;
}

Then you can use that:

public JsonResult Post([FromBody]Vehicle[] vehicles)
{
    return vehicles;
}

With data like:

[
  {
    "color":"Blue",
    "type": "car"
    "miles":100,
    "vin":"1234"
  },
  {
    "color":"Red",
    "type": "car"
    "miles":400,
    "vin":"1235"
  },
  {
    "color":"Red",
    "type": "truck"
    "miles":400,
    "vin":"1235"
  }
]
dan richardson
  • 3,871
  • 4
  • 31
  • 38