5

Occasionally I encounter JSON structure like "'data': null". NSJSONSerialization turns those into NSNull, which is, to be honest quite annoying.

I understand the reason behind this - things like NSDictionary cannot contain nil value.

That's fine, however in those cases, I would rather see the element missing from the de-serialized data structure, which in many cases actually ease the handling. Is there an option or configuration that can be passed to NSJSONSerialization, and ask it to do exactly this - simply miss those nil's in the de-serialized data structure?

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54
  • You can always scan through the NSDictionary and delete NSNulls. (In fact, there's probably a "predicate" way to do this in one line.) But for NSJSONSerialization to automatically omit them would be a serious noncompliance with the JSON architecture. – Hot Licks Jul 31 '14 at 22:57

2 Answers2

3

I do not believe that is possible. The options you can pass to the class don't mention anything like that, and the intro to the class states All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

However, this can be used to your advantage. If you were updating a local instance of an object via a CRUD-type web api, empty options would likely not be passed at all in the JSON. However, if you needed to nil-ify a property on the local instance that is currently set to a value, if the server sets that attr to null in the JSON, you can easily check to see if the JSONSerialized object has that attr set to NSNull, where you couldn't if it was missing.

Your best bet, if you control the endpoint that is generating the JSON, is simply not to set the attr at all.

tl;dr "no."

greymouser
  • 3,133
  • 19
  • 22
0

No, you can’t do that, because there is a semantic difference between an absent (read: “undefined”) value, and an explicitly defined null value.

While some (many?) JSON APIs may not make this distinction, that is in general not desirable: If you as an API provider use absence of an attribute to perform deletion on your consumer side, this requires you to always send complete entities in your responses.

If your entities have many attributes, and you have a few more of them this can have quite huge effects on the amount of data you have to hoist over to your clients.

Also, if you introduce a bug such that one of these attributes is missing temporarily, you start messing up your consumer’s client side data with every request you serve them…

Also, filtering out nulls yourself is fairly straight forward…

danyowdee
  • 4,658
  • 2
  • 20
  • 35
  • That's why he (and me, too) is asking for a parser option to ignore keys with "null" JSON values. – osxdirk Sep 26 '19 at 10:42