TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | MIT |
ReleasedLast Release | Dec 2014 |
Maintained by Unclaimed.
Set of categories on Foundation objects that simplify your life while working on parsed JSON objects.
Typical workflow while working with JSON looks like this:
NSError *error = nil;
NSData *JSONData = [self populateJSONData];
id JSONObject = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&error];
Class expectedClass = [NSDictionary class];
if ([JSONObject isKindOfClass:expectedClass]) {
[self processJSONDictionary:(NSDictionary *)JSONObject];
}
You see? All your code is scattered with -isKindOfClass:
. This protects your app from crashes when JSON data changes a bit. However in a JSON heavy application these cast operations produce a lot of unnecessary noice and you can't read your code fluently.
That's why JSON Safe was created. You can work with your JSON safely:
// produces NSDictionary or nil if there was no NSDictionary parsed
NSDictionary *JSONDict = [JSONObject mr_toDictionary];
Following conversions of an arbitrary JSON object are supported:
NSNull
always gets converted to nil
, no matter what are you trying to get: NSString
, NSNumber
, NSArray
or NSDictionary
.
Attempt to convert NSNumber
to NSNumber
yield same object. To NSString
— invoke -[NSNumber stringValue]
. To NSArray
— produce NSArray
containing the receiver. To NSDictionary
— nil
.
Similar things happen with NSString
:
NSString
→ NSString
gives the same objectNSNumber
uses NSNumberFormatter
with decimal separator set to .
NSArray
yields to @[ self ]
NSDictionary
returns nil
A bit tricky stuff happens with NSArray
and NSDictionary
. Here are NSArray
conversion rules:
NSArray
to NSString
gives you concatenated\n\content\nof\nthe\narray
NSNumber
outcomes in nil
NSArray
yields self
NSDictionary
— nil
And finally NSDictionary
:
nil
NSArray
results @[ self ]
NSDictionary
— self
The project is covered with set of tests that act like documentation. Go check it in tests/
directory.
Add following lines to your Podfile
:
pod 'MRJSONSafe'
Then run pod install
.
Or just copy src/MRJSONSafe.h
and src/MSJSONSafe.m
to your project if you don't bother to use CocoaPods.
The original idea was developed by Michael Efimov while working on Yandex.Search for iPhone application. Currently the project is maintained by Roman Busyghin.
Want something to be changed? Clone repo, write code, tests and documentation then submit pull request.
MRJSONSafe is available under the MIT license. See the LICENSE file for more info.