Last active
August 29, 2015 14:19
-
-
Save laynemoseley/22c4994af36955619f86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mantle is a framework that allows you to interchange JSON formatted data into model objects. | |
// You can read more about it here: https://github.com/Mantle/Mantle | |
// Using mantle is simple, create an object that inerhits from MTLModel, and it must also implement MTLJSONSerializing protocol. | |
#import <Mantle/Mantle.h> | |
@interface ModelObject : MTLModel <MTLJSONSerializing> | |
@property (nonatomic) NSString *name; | |
@property (nonatomic) NSString *zipCode; | |
@end | |
@implementation LMDrug | |
+ (NSDictionary *)JSONKeyPathsByPropertyKey { | |
return @{}; | |
} | |
@end | |
// That's all you need! | |
// Given JSON that looks like this: | |
// { | |
// "name": "Caleb Hicks", | |
// "zipCode": "84062" | |
// } | |
// | |
// You can turn that into your model object with the following code | |
NSError *error = nil; | |
NSDictionary *data = @{@"name": @"Caleb Hicks", @"zipCode", @"84062"}; | |
ModelObject *model = [MTLJSONAdapter modelOfClass:[ModelObject class] fromJSONDictionary:data error:&error]; | |
// To turn the model object back into JSON, use the following code: | |
NSDictionary *data = [MTLJSONAdapter JSONDictionaryFromModel:model]; | |
// If you have an array of objects, you can use this code | |
NSArray *arrayOfModels = [MTLJSONAdapter modelsOfClass:[ModelObject class] fromJSONArray:arrayOfThings error:&error]; | |
// Make sure to always handle the errors | |
if (error) { | |
// Handle Error | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment