将JSON数据映射到Object(包括CoreData)

本文介绍如何将JSON数据映射到Objective-C的Object,特别讨论了ObjectMapping的概念,包括处理属性映射及如何处理包含CoreData的对象映射。
摘要由CSDN通过智能技术生成

PropertyMapping

在进行数据的映射之前,我们需要定义Object(本文中所有Object都表示一个复杂的Object对象)中每一个property的映射关系PropertyMapping,其中ObjectMapping是标示当前property是否是一个Object,如果是nil,则表示当前property就是简单的映射。如果不是nil,则需要将property进行展开,把当前的property当成另外一个Object进行映射。

#import <Foundation/Foundation.h>

@class ObjectMapping;

@interface PropertyMapping : NSObject

@property (nonatomic, weak) ObjectMapping *objectMapping;
@property (nonatomic, copy) NSString *sourceKeyPath;
@property (nonatomic, copy) NSString *destinationKeyPath;

+ (PropertyMapping *)propertyMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(ObjectMapping *)mapping;

@end
#import "PropertyMapping.h"

@implementation PropertyMapping

+ (PropertyMapping *)propertyMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(ObjectMapping *)mapping
{
    PropertyMapping *propertyMapping = [self new];
    propertyMapping.sourceKeyPath = sourceKeyPath;
    propertyMapping.destinationKeyPath = destinationKeyPath;
    propertyMapping.objectMapping = mapping;
    return propertyMapping;
}

@end

ObjectMapping

ObjectMapping管理整个Object的PropertyMapping,包括objectClass,propertyMappings。并且提供Object反映射的inverseMapping。
#import <Foundation/Foundation.h>

@class PropertyMapping;

@interface ObjectMapping : NSObject

- (ObjectMapping *) initWithClass:(Class) objectClass;
- (ObjectMapping *) inverseMapping;
- (void) addPropertyMapping:(PropertyMapping *) porpertyMapping;
//add simple propertys 
- (void) addPropertyMappingsFromDictionary:(NSDictionary *) dic;

@end
#import "ObjectMapping.h"


@interface ObjectMapping ()
@property (nonatomic, readwrite) Class objectClass;
@property (nonatomic, readwrite) NSMutableArray *propertyMappings;
@property (nonatomic, readwrite) NSMutableArray *mappedKeyPaths;
@end

@implementation ObjectMapping

+ (instancetype)mappingForClass:(Class)objectClass
{
    return [[self alloc] initWithClass:objectClass];
}

- (id)initWithClass:(Class)objectClass
{
    self = [super init];
    if (self)
    {
        self.objectClass = objectClass;
        self.propertyMappings = [NSMutableArray new];
        self.mappedKeyPaths = [NSMutableArray new];
    }
    
    return self;
}

- (void)addPropertyMapping:(PropertyMapping *)porpertyMapping
{
    NSAssert([self.map
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值