【问题标题】:How to Get json data in a single object while post from Rest Client?从 Rest Client 发布时如何在单个对象中获取 json 数据?
【发布时间】:2017-12-01 11:03:41
【问题描述】:

我有以下我在 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?

【问题讨论】:

  • 您是只对 JSON 中的汽车感兴趣,还是对整个对象感兴趣?
  • 我需要一个对象中的 json,从中我可以在服务器端获取 Cars 参数值,如颜色、里程、vin 等。
  • 是的,我需要一个完整的对象。
  • 如果您传递相同的数据但不同的车辆类型,您可能最好传递车辆类型有一个值而不是属性字段,如"type": "car""type": "truck" 并将它们传递到内部"vehicles": [] 数组
  • 是的,好吧..但我没有在单个对象中获取 json 数据。

标签: c# json api web


【解决方案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"
  }
]

【讨论】:

    【解决方案2】:

    如果您需要将整个 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2021-11-24
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      相关资源
      最近更新 更多