列表/数组是否有效JSON? [英] Is a list/array valid JSON?

查看:121
本文介绍了列表/数组是否有效JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望编写一个提供JSON对象列表的Web服务。返回以下内容是否有效JSON:

I wish to write a webservice which serves lists of JSON objects. Is it valid JSON to return the following:

[
  {"keyA1":"valA", "keyB1":"valB"}
 ,{"keyA2":"valA", "keyB2":"valB"}
 ,{"keyA3":"valA", "keyB3":"valB"}
]

或者是正确的方式将它放在一个对象中返回:

Or is the "right" way to do it to put it in a single object to return:

{"elements":[
   {"keyA1":"valA", "keyB1":"valB"}
  ,{"keyA2":"valA", "keyB2":"valB"}
  ,{"keyA3":"valA", "keyB3":"valB"}
]}


推荐答案

两种表格均有效。但是,对于API,我建议使用第二种形式。原因是它为您提供了扩展API的途径。

Both forms are valid. However, for an API, I would recommend the second form. The reason is that it gives you a path for expansion of your API.

例如,如果您有API getUsersInGroup 返回一个用户对象数组,稍后您决定要包含一些关于返回用户的聚合统计信息,没有简单的方法可以在不破坏现有客户端的情况下执行此操作(或者在每个客户端中包含大量冗余数据)用户对象)。如果您使用对象,则只需向该对象添加另一个字段,该字段在以前版本的API上被客户端静默忽略。

For example, if you have an API getUsersInGroup which returns an array of user objects, and later you decide you want to include, say, some aggregate statistics about the users being returned, there's no easy way to do that without breaking existing clients (or including lots of redundant data in each user object). If you use an object, you simply add another field to the object which is silently ignored by clients on a previous version of the API.

简而言之,尽量避免使用top在您的API中尽可能使用-level基元,并且您将来会发现它更容易扩展。

In short, try to avoid top-level primitives wherever possible in your API, and you'll find it easier to expand in the future.

这篇关于列表/数组是否有效JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆