来自 REST API 的 JSON 响应中是否应该包含空值? [英] Should null values be included in JSON responses from a REST API?

查看:44
本文介绍了来自 REST API 的 JSON 响应中是否应该包含空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计和开发 RESTful API.我正在对 API 采取务实的、面向资源的方法(面向资源、统一接口、可寻址性,但没有真正的 HATEOAS).我不确定的一点是如何处理对象中的空值.

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.

我是否应该在 API 响应中包含具有空值的字段?

示例:

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

或者,如果系统没有这些字段的数据,我是否应该完全忽略这些字段?

示例:

{
    "fieldA": "AAA"
}

推荐答案

最近在 API 工艺.普遍的共识是,省略值与包含空值之间可能存在语义差异.

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 目标消费者,并考虑省略该价值是否会导致他们出现问题.

If there is no semantic value to be gained for your specific use case, then I would say look at your target consumers of the API, and think about whether omitting the value will cause them problems.

这篇关于来自 REST API 的 JSON 响应中是否应该包含空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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