Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization and NSNull

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?

like image 306
Peter Pei Guo Avatar asked Oct 20 '22 04:10

Peter Pei Guo


1 Answers

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

like image 176
greymouser Avatar answered Nov 03 '22 00:11

greymouser