TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | MIT |
ReleasedLast Release | Jun 2016 |
Maintained by Alexey Nazaroff.
Depends on: | |
ODX.Core | ~> 1.5 |
ODObjCRuntime | ~> 1.1 |
ODX.Serialization is utility classes for serialization and deserialization Objective-C objects. It can be used together with NSJSONSerialization or XMLDictionary, FMDB, etc.
(NSObject+ODSerialization)
<NSObject> -(id)od_serialize;
Converts any object to NSDictionary or NSArray with NSStrings, NSNumbers and NSNulls. After this new object can be converted to JSON string.
(NSObject+ODDeserialization)
<NSObject> +od_constructWithObject:(NSObject *)srcObj error:(NSError **)error;
Create object of current class from NSDictionary. Using that it's possible to convert json string to model object.
Let's create our model class:
@interface Obj : NSObject <ODDataObject>
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) NSArray<Obj *> *items;
@end
@implementation Obj
// We implement ODDataObject protocol's method for specify class of object in `items` array
+ (Class)classOfIvarWithName:(NSString *)ivarName {
if ([ivarName isEqualToString:@"_items"]) return Obj.class;
return nil;
}
@end
Now, if we fill object and perform od_serialize
method:
Obj *o = [Obj new];
o.title = @"Title";
o.count = 10;
o.items = @[[Obj new], [Obj new]];
NSLog(%"@", o.od_serialize);
/*
{
count = 10;
items = (
{
count = 0;
items = "<null>";
title = "<null>";
},
{
count = 0;
items = "<null>";
title = "<null>";
}
);
title = Title;
}
*/
NSLog(@"%@", [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:o.od_serialize
options:0 error:nil]
encoding:NSUTF8StringEncoding]);
// {"title":"Title","count":10,"items":[{"title":null,"count":0,"items":null},{"title":null,"count":0,"items":null}]}
Deserialization.
NSString *jsonString = @"{\"title\":\"Title\",\"count\":10,\"items\":[{\"title\":null,\"count\":0,\"items\":null},{\"title\":null,\"count\":0,\"items\":null}]}";
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
Obj *obj = [Obj od_constructWithObject:obj error:nil];
For build ODX.Serialization as library you need to put ODObjcRuntime and ODX.Core projects in the same directory
Alexey Nazaroff, [email protected]
ODX.Serialization is available under the MIT license. See the LICENSE file for more info.