About Mantle
Mantle is a powerful and flexible framework for parsing and mapping JSON to Objective-C objects. It eliminates the need for writing boilerplate code and provides a simple and elegant solution for working with JSON APIs in Cocoa and Cocoa Touch applications.
Key Features
- Automatic JSON serialization and deserialization.
- Direct mapping of JSON keys to Objective-C object properties.
- Easily handle complex JSON structures.
- Supports nested objects and arrays.
- Transform values during serialization and deserialization.
- Validation of JSON data.
- Straightforward integration with popular networking libraries like AFNetworking and NSURLSession.
Getting Started
Installation
To install Mantle using CocoaPods, add the following line to your Podfile:
pod 'Mantle'
Usage
1. Import the Mantle framework in your Objective-C class:
#import <Mantle/Mantle.h>
2. Create a subclass of MTLModel
and implement the MTLJSONSerializing
protocol:
// MyModel.h
@interface MyModel : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSDate *createdAt;
@property (nonatomic, assign) NSInteger followersCount;
@end
// MyModel.m
@implementation MyModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"name" : @"full_name",
@"createdAt" : @"created_at",
@"followersCount" : @"followers_count"
};
}
@end
3. Use the MTLJSONAdapter
class to convert your JSON data into an instance of your model:
NSDictionary *JSONDictionary = ...; // JSON data
NSError *error = nil;
MyModel *model = [MTLJSONAdapter modelOfClass:[MyModel class] fromJSONDictionary:JSONDictionary error:&error];
Resources
- GitHub Repository: Mantle
- Official Documentation: Mantle Documentation