Catalytic 提供了一种简单地将 JSON 数据映射到本地的 Objective-C 领域对象的方式。
以下是一些领域对象示例,即 ModelObject
和 NestedObject
。
// ModelObject.h
#import <Foundation/Foundation.h>
@class NestedObject;
@interface ModelObject : NSObject
@property (nonatomic, readonly) NSArray<NSString *> *strings;
@property (nonatomic, readonly) NestedObject *nestedObject;
@property (nonatomic, readonly) NSArray<NestedObject *> *nestedObjects;
@end
// NestedObject.h
#import <Foundation/Foundation.h>
@interface NestedObject : NSObject
@property (nonatomic, readonly, copy) NSString *string;
@property (nonatomic, readonly) NSInteger integer;
@end
Catalytic
可以轻松地将这些对象的相应 JSON 表示映射到上面给出的本地字段。
{
"type": "model_object",
"nested_object": {
"type": "nested_object",
"string": "0",
"integer": 0
},
"nested_objects": [
{
"type": "nested_object",
"string": "1",
"integer": 1
},
{
"type": "nested_object",
"string": "2",
"integer": 2
}
],
"strings": [
"abc",
"bbd"
]
}
首先设置一个 id <CTTypeProvider>
实例来处理包含字典到领域对象类的映射。
// TypeProvider.m
#import "TypeProvider.h"
#import "ModelObject.h"
#import "NestedObject.h"
@implementation TypeProvider
- (Class)typeOfObject:(id)object
containerClass:(__unsafe_unretained Class)containerClass
referencingKey:(NSString *)key
fieldType:(CTConverterFieldType)fieldType {
if ([[object valueForKey:@"type"] isEqualToString:@"model_object"]) {
return [ModelObject class];
} else if ([[object valueForKey:@"type"] isEqualToString:@"nested_object"]) {
return [NestedObject class];
} else {
return NULL;
}
}
@end
然后从给定的 JSON 中恢复解析后的领域对象是一个简单的过程。
id <CTTypeProvider> typeProvider = [[TypeProvider alloc] init];
CTConverter *converter = [[CTConverter alloc] initWithFieldNamingPolicy:CTConverterFieldNamingPolicyLowerCaseWithUnderscores
typeProvider:typeProvider];
NSDictionary *jsonDictionary = ({
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"model_object" ofType:@"json"];
NSData *jsonData = [[NSData alloc] initWithContentsOfFile:jsonPath];
[NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
});
NSError * __autoreleasing error;
ModelObject *modelObject = [converter convert:jsonDictionary error:&error];