简体   繁体   English

[]是一种在json结果中表示空值的有效方法吗?

[英]Is [] a valid way to represent a null value in a json result?

I am trying to consume a 3rd party JSON API, and was expected that a null value would have no value at all provided, left out of the result, or some default. 我正在尝试使用第三方JSON API,并且期望空值根本没有提供任何值,从结果中删除,或者某些默认值。 Instead the API returns back [] in place of a single value (not something that would be an array) if the value doesn't exist: 相反,如果值不存在,API将返回[]代替单个值(不是数组):

"SomeExpectedDate": [],
"SomeExpectedString": [],
...

When I try to deserialize this using JayRock JsonConvert, it fails since i'm trying to load into single String or DateTime values. 当我尝试使用JayRock JsonConvert对其进行反序列化时,它会失败,因为我正在尝试加载到单个String或DateTime值。

Is this normal, or should I go complain to the API provider (this is a recently introduced API) 这是正常的,还是应该向API提供者投诉(这是最近推出的API)

In general, no. 一般来说,没有。 In JSON [] indicates an empty array. 在JSON []表示一个空数组。 If you want to represent a null value, use the null keyword. 如果要表示空值,请使用null关键字。 Like: 喜欢:

{"someString": null}

Although in terms of how you want to represent a null value in your JSON, that is entirely up to you. 虽然就您希望如何在JSON中表示空值而言,这完全取决于您。 If you write the receiving code so that it understands that an empty array is equivalent to null, that will certainly work. 如果您编写接收代码以便它理解空数组等于null,那肯定会有效。

In my opinion however that would be a very questionable/unreliable/difficult maintain approach. 但在我看来,这将是一个非常可疑/不可靠/困难的维护方法。 It makes a lot more sense to use the null keyword, or failing that, an empty string ( {"someString": ""} ). 使用null关键字或者失败,使用空字符串( {"someString": ""} )会更有意义。

Edit: 编辑:

To respond to your update about this issue being related to consuming a third-party API, I think definitely this is an issue to take up with the API provider. 要回复有关与使用第三方API相关的此问题的更新,我认为这绝对是一个需要使用API​​提供程序的问题。 They should not be returning [] if what they really mean is null . 如果他们真正意味着什么是null他们不应该返回[] While what they're sending is technically still valid JSON, it's semantically questionable for them to be using [] instead of null . 虽然他们发送的内容在技术上仍然是有效的JSON,但是在语义上他们使用[]而不是null

If the third party API you are using says that an empty array is null, then that is perfectly valid and you need to write your code around it. 如果您使用的第三方API表示空数组为空,那么这完全有效,您需要围绕它编写代码。

It is certainly different from anything I've seen before, since json has an actual null keyword, but it is perfecly legal syntax. 它肯定不同于我以前见过的任何东西,因为json有一个实际的null关键字,但它是完全合法的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM