如何从Web API 2发送命名的JSON对象?

时间:2018-08-05 21:14:57

标签: c# asp.net-web-api asp.net-web-api2

目前,我的Web API将JSON数据作为UNNAMED对象数组发送,如下所示:

[
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Provider Frame",
    "memberCost": 75.00,
    "providerCost": 25.00
  },
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Customer Frame",
    "memberCost": 0.00,
    "providerCost": 0.00
  },
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Fireproof Frame",
    "memberCost": 75.00,
    "providerCost": 25.00
  }
]

是否可以更改API来发送像这样的数据?

{
  "frames": [
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Provider Frame",
    "memberCost": 75.00,
    "providerCost": 25.00
  },
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Customer Frame",
    "memberCost": 0.00,
    "providerCost": 0.00
  },
  {
    "productTypeId": 1,
    "productCategoryId": 4,
    "name": "Fireproof Frame",
    "memberCost": 75.00,
    "providerCost": 25.00
  }
 ]
}

我想让前端框架能够按名称读取JSON对象,而不是假定它是“数据”。这有道理吗?

以下是Web API的代码:

public sealed class FramesController : ApiController
    {
        private readonly IProductService prodSvc;
        public FramesController(IProductService _prodSvc)
        {
            prodSvc = _prodSvc;
        }


        public IEnumerable<Product> GetFrames(int productTypeId)
        {
            return prodSvc.GetProductsByCategoryId((int)Enums.CategoryGroup.Frame, productTypeId);
        }
    }

3 个答案:

答案 0 :(得分:1)

更新操作以返回封装在具有所需属性名称的对象中的数据

public sealed class FramesController : ApiController {
    private readonly IProductService prodSvc;

    public FramesController(IProductService _prodSvc) {
        prodSvc = _prodSvc;
    }


    public IHttpActionResult GetFrames(int productTypeId) {
        var products = prodSvc.GetProductsByCategoryId((int)Enums.CategoryGroup.Frame, productTypeId);

        if(!products.Any())
            return NotFound();

        var result = new { frames = products.ToArray() };
        return Ok(result);
    }
}

上面的示例使用匿名类型,但可以像

这样使用具体类型
public class GetFramesResult {
    public Product[] frames { get; set; }
}

并用于操作

var result = new GetFramesResult { frames = products.ToArray() };

答案 1 :(得分:0)

用一个类包装您的响应类型,并给它一个名为“ frames”的数组属性,它具有框架类的类型。

http://json2csharp.com/获得帮助

您应该返回YourResponse类的实例,如下所示:

public class Frame
{
    public int productTypeId { get; set; }
    public int productCategoryId { get; set; }
    public string name { get; set; }
    public double memberCost { get; set; }
    public double providerCost { get; set; }
}

public class YourResponse
{
    public List<Frame> frames { get; set; }
}

答案 2 :(得分:0)

您可以使用ExpandoObject:

dynamic data = new ExpandoObject();
data.frames = yourObject;
return Json(data);