如何从Rest Client发布时在单个对象中获取json数据?

时间:2017-06-28 07:42:53

标签: c# json api web

我有以下在RestClient中使用的json数据发布。

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

我试图在服务器端的单个对象中获取此json,同时从Rest Client发布

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

如何在单个对象中获取此json?

2 个答案:

答案 0 :(得分:0)

如果您需要将整个JSON添加到对象中,那么我在这里使用json2csharp.com将您的JSON转换为类。

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; }
}

将您的API更改为:

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

现在,您可以访问Carstruck

答案 1 :(得分:-1)

以前曾多次询问过这个问题:Posting array of objects with MVC Web API

您可能最好使用类来表示对象

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

然后你可以使用它:

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

使用以下数据:

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