ODX.Serialization 1.6.1

ODX.Serialization 1.6.1

测试已测试
语言语言 Obj-CObjective C
许可协议 MIT
发布最后发布2016年6月

Alexey Nazaroff维护。



 
依赖项
ODX.Core~> 1.5
ODObjCRuntime~> 1.1
 

  • Alexey Nazaroff

ODX.Serialization 是 Objective-C 对象序列化和反序列化的实用类。它可以与 NSJSONSerialization、XMLDictionary、FMDB 等一起使用。

用法

序列化

(NSObject+ODSerialization)

<NSObject> -(id)od_serialize;

将任何对象转换为 NSDictionary 或 NSArray,其中包含 NSStrings、NSNumbers 和 NSNulls。之后,新对象可以被转换为 JSON 字符串。

反序列化

(NSObject+ODDeserialization)

<NSObject> +od_constructWithObject:(NSObject *)srcObj error:(NSError **)error;

从 NSDictionary 创建当前类的对象。通过这种方式,可以将 json 字符串转换为模型对象。

示例

让我们创建我们的模型类

@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

现在,如果我们填写对象并执行 od_serialize 方法

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}]}

反序列化。

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];

Object debug

安装

手动

要在同一目录下构建 ODX.Serialization 作为库,您需要将 ODObjcRuntimeODX.Core 项目放入同一目录中

作者

Alexey Nazaroff,[email protected]

许可协议

ODX.Serialization 可在 MIT 许可协议下获得。有关更多信息,请参阅 LICENSE 文件。