A basic class for mapping JSON objects to their models. Also fully compliant w/ NSCoding
automatically. The only thing you need to do is subclass the model, declare your properties, and then override mapping using the following syntax:
- (NSMutableDictionary *)mapping {
NSMutableDictionary *mapping = [super mapping];
mapping[@"propertyName"] = @"associatedJSONKey";
}
If your property maps to another JSONMappableObject
, or an array of them, use the following syntax for your mapping key:
@``<#propertyName#>``:``<#ClassName#>
- (NSMutableDictionary *)mapping {
NSMutableDictionary *mapping = [super mapping];
mapping[@"@propertyName:TypeOfClass"] = @"associatedJSONKey";
}
In the future, I will add the introspection necessary to get the class type and avoid having to change this, but for now, just specify the class.
###Example
GIGitHubIssue.h
#import "JSONMappableObject.h"
@class GIGitHubUser;
@class GIGitHubIssueMilestone;
@class GIGitHubPartialPullRequest;
@interface GIGitHubIssue : JSONMappableObject
@property (nonatomic) NSInteger identifier;
@property (copy, nonatomic) NSString *apiURL;
@property (copy, nonatomic) NSString *htmlURL;
@property (nonatomic) NSInteger number;
@property (copy, nonatomic) NSString *state;
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *bodyMarkdown;
@property (strong, nonatomic) GIGitHubUser *user;
@property (strong, nonatomic) NSArray *labels; // GIGitHubIssueLabel
@property (strong, nonatomic) GIGitHubUser *assignee;
@property (strong, nonatomic) GIGitHubIssueMilestone *milestone;
@property (strong, nonatomic) GIGitHubPartialPullRequest *pullRequest;
@property (nonatomic) NSInteger commentCount;
@property (copy, nonatomic) NSString *closedAt;
@property (copy, nonatomic) NSString *createdAt;
@property (copy, nonatomic) NSString *updatedAt;
@property (nonatomic) BOOL locked;
@end
GIGitHubIssue.m
#import "GIGitHubIssue.h"
@implementation GIGitHubIssue
- (NSMutableDictionary *)mapping {
NSMutableDictionary *mapping = [super mapping];
mapping[@"identifier"] = @"id";
mapping[@"apiURL"] = @"url";
mapping[@"htmlURL"] = @"html_url";
mapping[@"number"] = @"number";
mapping[@"state"] = @"state";
mapping[@"title"] = @"title";
mapping[@"bodyMarkdown"] = @"body";
mapping[@"@user:GIGitHubUser"] = @"user";
mapping[@"@labels:GIGitHubIssueLabel"] = @"labels";
mapping[@"@assignee:GIGitHubUser"] = @"assignee";
mapping[@"@milestone:GIGitHubIssueMilestone"] = @"milestone";
mapping[@"commentCount"] = @"comments";
mapping[@"@pullRequest:GIGitHubPartialPullRequest"] = @"pull_request";
mapping[@"closedAt"] = @"closed_at";
mapping[@"createdAt"] = @"created_at";
mapping[@"updatedAt"] = @"updated_at";
mapping[@"locked"] = @"locked";
return mapping;
}
@end