一个小型库,可以解析 JSON 并将其映射到任何对象,支持 NSManagedObject。
@interface User : NSObject
@property (nonatomic, strong) NSNumber *userID;
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSDate *createdAt;
@end
[BWObjectMapping mappingForObject:[User class] block:^(BWObjectMapping *mapping) {
[mapping mapPrimaryKeyAttribute:@"id" toAttribute:@"userID"];
[mapping mapKeyPath:@"first_name" toAttribute:@"firstName"];
[mapping mapKeyPath:@"created_at" toAttribute:@"createdAt"];
[[BWObjectMapper shared] registerMapping:mapping withRootKeyPath:@"user"];
}];
在最末行我们注册了映射并给出根键路径。您不必一定有它,但是如果没有,映射器将无法猜测要使用哪个映射类。
[[BWObjectMapper shared] objectWithBlock:^id(Class objectClass, NSString *primaryKey, id primaryKeyValue, id JSON) {
return [[objectClass alloc] init];
}];
{
"user": [{
"id": 1,
"first_name": "Bruno",
"created_at": "2012-08-10T06:12:28Z"
}]
}
默认解析日期格式是 Rails 格式。
NSArray *objects = [[BWObjectMapper shared] objectsFromJSON:JSON];
因为 JSON 包含根键路径,映射自动发现。
- (NSArray *)objectsFromJSON:(id)JSON withMapping:(BWObjectMapping *)mapping;
- (NSArray *)objectsFromJSON:(id)JSON withObjectClass:(Class)objectClass;
- (NSArray *)objectsFromJSON:(id)JSON;
- (id)objectFromJSON:(id)JSON withMapping:(BWObjectMapping *)mapping;
- (id)objectFromJSON:(id)JSON withMapping:(BWObjectMapping *)mapping existingObject:(id)object;
- (id)objectFromJSON:(id)JSON withObjectClass:(Class)objectClass;
- (id)objectFromJSON:(id)JSON withObjectClass:(Class)objectClass existingObject:(id)object;
- (id)objectFromJSON:(id)JSON;
- (id)objectFromJSON:(id)JSON existingObject:(id)object;
如果您不使用 Rails 日期格式,您有两个选项
指定全局日期格式
[objectMapping mapKeyPath:@"created_at" toAttribute:@"createdAt" dateFormat:@""];
在每个属性上自定义日期格式。
[[BWObjectMapper shared] setDefaultDateFormat:@""];
将 BWObjectMapper 目录复制到您的 项目 中。
BWObjectMapper 是 ARC 的。
Bruno Wernimont