TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | Apache 2 |
ReleasedLast Release | Nov 2015 |
Maintained by Patrick Hogan.
Catalytic provides a simple way to map JSON data onto native Objective-C domain objects.
Consider the following examples of domain objects, ModelObject
and 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
can easily map the corresponding JSON representation of these objects onto the native fields given above.
{
"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"
]
}
First set up a id <CTTypeProvider>
instance to handle the mapping of contained dictionaries to domain object classes.
// 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
Then it is a straightforward exercise to recover a parsed domain object from the given 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];