سؤال

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. Instead the API returns back [] in place of a single value (not something that would be an array) if the value doesn't exist:

"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.

Is this normal, or should I go complain to the API provider (this is a recently introduced API)

هل كانت مفيدة؟

المحلول

In general, no. In JSON [] indicates an empty array. If you want to represent a null value, use the null keyword. Like:

{"someString": null}

Although in terms of how you want to represent a null value in your JSON, that is entirely up to you. If you write the receiving code so that it understands that an empty array is equivalent to null, that will certainly work.

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": ""}).

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. They should not be returning [] if what they really mean is null. While what they're sending is technically still valid JSON, it's semantically questionable for them to be using [] instead of 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.

It is certainly different from anything I've seen before, since json has an actual null keyword, but it is perfecly legal syntax.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top