I'm curious, I currently have an NSDictionary
where some values are set to an NSNull
object thanks to the help of json-framework.
The aim is to strip all NSNull
values and replace it with an empty string.
I'm sure someone has done this somewhere? No doubt it is probably a four liner and is simple, I am just far too burnt out to figure this out on my own.
Thanks!
Rolling through the dictionary hunting for NSNull is one way to tackle the problem, but I took a slightly lazier approach. Instead of nil you could assign an empty string, but the principle is the same.
CPJSONDictionary.h
CPJSONDictionary.m
A category on nsnull that returns nil seems to also sense, at least to me. There are a few out there. One makes all calls return nil which seems to make sense. Sorry no link. I guess if you need to later use nspropertylistserialization the category might not work for you.
I have tested Stakenborg solution. It works well, but it has following problem. If some object is expected to be number, for instance, converting it to
NSNull
can be a source of error. I have create a new method to directly remove theNSNull
entries. This way you only have to check that correspondant key exists.Add in
NSDictionary+NullReplacement
And in
NSArray+NullReplacement
I hope this helps
Here is my solution:
I've made a few changes to Jacob's original answer to extend it to handle dictionaries and arrays stored within the original dictionary.
And there's also an array category of course:
With this, you can take any array or dictionary and recursively wipe out all the [NSNull null] instances.
Hope it helps someone.
-Brandon
P.S. For completion's sake, here are the header files:
And the array header: