In the process of iOS development, data communication with the server is often needed, and Json is a common efficient and simple data format. But several projects have been encountered a pit problem, the program in the acquisition of some data after inexplicable crash. The reason was discovered a long time ago: some fields in the server’s database were empty and were returned to the client as Json:

"somevalue":null
Copy the code

The data parsed through JsonKit, a third-party library, is

somevalue = "<null>";
Copy the code

This data type is not nil and it’s not a String. After parsing into objects, sending messages directly to the object (eg: Length, count, etc.) will crash. Error: -[NSNull length]: unrecognized selector sent to instance 0x388a4a70

The solution actually didn’t find the perfect solution for me for a long time. If (! = null) {if (! = null) {if (! = null); [isKindOfClass:[NSNull class]]){xxxxxxx; }

Because the field is too much, I find a fill one. 2. To solve this problem completely, I decided to start from the data source. In fact, I should be able to match the null with a regular expression and then replace it. So a copycat approach came up: string matching. When we get Json from the server, the result is a string, so we replace null with a null character “”, and then parse.

json = [jsonStr  stringByReplacingOccurrencesOfString:@":null" withString:@": \" \ ""];
Copy the code

This method would have worked well, but my server is returning a lot of junk data… This will cause the JSON to become unparsed anyway. 3. In the end, there’s no other way to do this than to parse and replace a value of type NSNull with nil. You usually write a tool method and call it when parsing. Macros can also return values. The result is as follows:

#define VerifyValue(value)
({id tmp;
if ([value isKindOfClass:[NSNull class]])
tmp = nil;
else
tmp = value;
tmp;
})
Copy the code

The last statement in the macro is the return value. The macro is then called when the data is parsed:

contact.contactPhone = VerifyValue(contactDic[@"send_ContactPhone"]);
Copy the code

4. If you use the AFNetwork library for network requests, you can use the following code to automatically remove this annoying null value for you

self.removesKeysWithNullValues = YES; NullSafe is a Category that operates at runtime and sets this annoying null value to nil. Nil is safe and can send any message to a nil object without crashing. It's a very easy category to use, you just add it to the project, you don't have to do anything else, yeah, it's that simple. For details, please go to Github. [https://github.com/nicklockwood/NullSafe] (https://github.com/nicklockwood/NullSafe), the original address: [http://www.pan-apps.com/668.html](http://www.pan-apps.com/668.html)Copy the code