MugunthKumar / MKNetworkKit

Modern NSURLSession based Networking Framework with built in authentication and HTTP 1.1 caching standards support for iOS 8+ devices
http://mk.sg/8w
3.06k stars 755 forks source link

responseJSON would be better as mutable #371

Open dbiollo opened 11 years ago

dbiollo commented 11 years ago

Often, with parsing a JSON response from server, it's useful to strip out all NSNull values (from dictionaries), in order to avoid repetitive coding to avoid NSNull. One can easily strip out NSNull recursively from a NSMutableDictionary.

Currently responseJSON returns an immutable dictionary/array. This is less than convenient since it's a very tedious process to create a deep mutable copy.

A simple solution is to parse the JSON with MutableContainers option. Here is the change to MKNetworkOperation.m:

 -(id) responseJSON {
+  NSJSONReadingOptions options = NSJSONReadingMutableContainers;

   if([self responseData] == nil) return nil;
   NSError *error = nil;
-  id returnValue = [NSJSONSerialization JSONObjectWithData:[self responseData] options:0 error:&error];
+  id returnValue = [NSJSONSerialization JSONObjectWithData:[self responseData] options:options error:&error];
   if(error) DLog(@"JSON Parsing Error: %@", error);
   return returnValue;
 }
Juraldinio commented 11 years ago

I think, better solution is subclass MKNetworkOperation and make with it what you need to do =) Also all you need to do - is define in object of MKNetworkEngine your custom MKNetworkOperation by sending registerOperationSubclass: message

dbiollo commented 11 years ago

That's a good suggestion for working around this and it works. Although I'd argue that it would still be beneficial to update the main behaviour. Don't really see a downside to producing mutable containers and -(id)responseJSON generates a new hash/array every time its called. Imagine many clients will want to strip out NSNull from REST responses ... it's generally a headache to deal with ...