JSONから生成したNSDictionaryをオブジェクトにマッピングするのって面倒ですよね。
こんなん。
NSDictionary *jsonDictionary = @{
@"id": @123,
@"username": @"taro yamada"
};
User *user = [[User alloc] init];
user.id = jsonDictionary[@"id"];
user.name = jsonDictionary[@"username"];
この手のマッピング用ライブラリはたくさんあるんですが、探した中ではRPJSONMapperが使いやすそうでした。
- マッピング定義が辞書で簡単に書ける
- マッピング定義を一箇所に書ける
- トランスフォーム(型変換)が出来る
例えばJSONリストをマッピングしてみる。
@implementation Note
@property(nonatomic, strong) NSString *title;
@property(nonatomic, strong) NSString *text;
@property(nonatomic, strong) NSDate *date;
@end
NSArray *notes = @[
// noteの辞書
@{
@"id": @123,
@"title": @"今日のランチ",
@"body": @"ジェノベーゼ",
@"posted_at": @"2014-05-14T15:55:30Z" // ISO8601形式
},
...
];
NSArray *array = [[RPJSONMapper sharedInstance] objectsFromJSONArray:notes
withInstantiationBlock:^id {
// マッピング先のオブジェクト
return [[Note alloc] init];
}
usingMapping:@{
@"id": @"id",
@"title" : @"title",
@"body" : @"text",
@"posted_at" : [[RPJSONMapper sharedInstance] boxValueAsNSDateIntoPropertyWithName:@"date" usingDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]
}];
その他のライブラリ
他のオブジェクトにマッピングしたり、文字列を数値にしたり、全然違う値にトランスフォームしたり、というのもやりたいので、調べて新しいことが分かったら更新します。