I'm in the process of designing and developing a RESTful API. I'm taking a pragmatic, resource oriented approach to the API (resource oriented, uniform interface, addressability, but no real HATEOAS). One point I'm not sure about though is how to approach null values in objects.

Should I include fields with null values in the APIs responses?

例子:

{
    "fieldA": "AAA",
    "fieldB": null
}

Or, should I just leave out these fields altogether if the system has no data for these fields?

例子:

{
    "fieldA": "AAA"
}

推荐答案

There was a discussion about this recently on API-Craft. The general consensus was there is potentially a semantic difference between the omission of a value, versus an inclusion of a null value.

如果您的特定用例没有可以获得的语义值,那么我会说查看API的目标消费者,并考虑省略该值是否会给他们带来问题.

Json相关问答推荐

需要Jolt规范将具有动态字段的输入json转换为输出json

如何形成正确的JQ表达式以从JSON文件中获得准确的输出数据?

Allof Indide的JSON模式之一

属性错误:';ActivitiesClient';对象没有属性';base_url';

无法访问id的第三级json

Oracle JSON 查询中的动态列列表

Ansible - 将文件内容添加到字典中

展平多个数组以保持顺序

Jolt规范:将嵌套数组中的null元素移除

具有 (RegEx) 模式的 json-schema 中的枚举

将 colly 包输出文本添加到 golang 中的映射

Oracle Apex - 将 JSON 对象分配给变量以返回

jq:来自嵌套 JSON 的映射

Vue 3如何将参数作为json发送到axios get

坚持弄清楚如何使用 api 响应来调用以从不同的链接检索响应

通过sql查询读取嵌套Json

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

在 JSON.stringify() 的输出中隐藏空值

JSON JQ 如果没有 else

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)