【问题标题】:Pros and Cons of using json array and json object使用 json 数组和 json 对象的优缺点
【发布时间】:2016-12-28 13:43:49
【问题描述】:

我的问题有点理论,但很有趣。 我想知道在使用 web api 时哪种方法最好。

我有两种方法

  1. 一个有List<Customer>作为参数

public void Create(List<Customer>) { //... }

  1. 第二个有CustomerList 作为参数(其中CustomerList 类有属性public List<Customer> customers {get; set;}

public void Create(CustomerList customer) { //... }

我知道方法 1 需要传递 json 数组,方法 2 需要将 json 数组包装到 json 对象。

但我的问题是哪种方法最好,为什么?

【问题讨论】:

  • 没有优缺点。如果您只想要客户,请使用List<Customer>。另一方面,如果您想要客户和其他数据,则使用后一种方法。

标签: c# asp.net json asp.net-mvc asp.net-web-api


【解决方案1】:

在涉及 API 时,我总是尽可能明确地说明它所公开的合同。因此,当您期望 List 时,请使用 JSON 数组。您的 API 用户会更清楚预期的内容。

话虽如此,使用 JSON 对象的优势在于,如果您稍后决定在请求中接受额外的属性,它不会是重大更改。

最后,这一切都取决于您的用例。这是否会成为暴露给其他人的端点,而不仅仅是您?您是否已经知道将来您将要接受附加数据以及客户列表?这些是您需要问自己的一些问题。

【讨论】:

  • 相当描述性的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 2018-07-03
相关资源
最近更新 更多