LoginSignup
23
23

More than 5 years have passed since last update.

RPJSONMapperでお手軽マッピング

Last updated at Posted at 2014-05-23

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'"]
                                                        }];

その他のライブラリ

  • JSONModel dot notationでアクセス出来るのが便利そう。トランスフォームはカスタムクラスで実装。
  • Mantle

他のオブジェクトにマッピングしたり、文字列を数値にしたり、全然違う値にトランスフォームしたり、というのもやりたいので、調べて新しいことが分かったら更新します。

23
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
23