2

我有一系列 NSObject,我想序列化为 JSON 并发布到服务。最终的对象由多个嵌套的这些 NSObject 子类组成。

这些对象中的每一个都遵循带有方法的协议,该方法使用适当的键返回 NSDictionary 中的对象属性。但是,其中一些属性是其他对象等等,使得序列化有点复杂。

有没有一种模式可以用来简化最终对象的序列化?使用 JSONKit,似乎我需要从最深的对象单独序列化每个字典并向后工作,检查错误,然后添加到复合字符串。我知道这不可能是使用这个功能强大的库的最佳方法。欢迎任何建议或指导。

编辑 1

JSONKit GitHub 网址

JSONKit 自述文件

4

3 回答 3

8

The AutomagicCoding library uses low-level property introspection to recursively convert any NSObject into an NSDictionary, which can then be directly serialised as JSON:

https://github.com/psineur/NSObject-AutomagicCoding

It may involve a bit of fine-tuning for classes with properties that are structs, etc, but it's probably the easiest, least labour-intensive approach you'll find.

UPDATE:

I've since written my own library, HRCoding (https://github.com/nicklockwood/HRCoder) that can load/save any object as JSON using the NSCoding protocol)

于 2012-02-08T17:34:41.680 回答
2

现在您可以使用JSONModel轻松解决这个问题。JSONModel 是一个基于 Class 对对象进行一般序列化/反序列化的库。您甚至可以使用基于非 nsobject 的属性,例如int,shortfloat. 它还可以满足嵌套复杂的 JSON。它为您处理错误检查。

鉴于此 JSON{"firstname":"Jenson","surname":"Button"}

反序列化示例。在头文件中:

#import "JSONModel.h"

@interface Person : JSONModel 
@property (nonatomic, strong) NSString* firstname;
@property (nonatomic, strong) NSString* surname;
@end

在实现文件中:

#import "JSONModelLib.h"
#import "yourPersonClass.h"

NSString *responseJSON = /*from somewhere*/;
Person *person = [[Person alloc] initWithString:responseJSON error:&err];
if (!err)
{
   NSLog(@"%@  %@", person.firstname, person.surname):
}

序列化示例。在实现文件中:

#import "JSONModelLib.h"
#import "yourPersonClass.h"

Person *person = [[Person alloc] init];
person.firstname = @"Jenson";
person.surname = @"Uee";

NSLog(@"%@", [person toJSONString]);
于 2013-05-27T09:43:45.577 回答
1

我不确定我是否理解这个问题。您要求一种模式,但您似乎描述了标准模式:

这些对象中的每一个都遵循带有方法的协议,该方法使用适当的键返回 NSDictionary 中的对象属性。

假设该方法被调用serializedDictionary。如果一个类的属性本身就是其他对象,您只需调用serializedDictionary并将结果添加到您正在构建的字典中。因此,您需要做的就是向顶级对象询问它的serializedDictionary​​ ,并将其转换为 JSON。

如果您担心错误处理,只需检查方法的结果并将错误传递给调用者即可。您可以通过例外(无需编写代码)或按照约定来执行此操作。例如,假设在错误时返回 nil 并通过引用指向 NSError 实例的指针。然后在您的容器对象中执行以下操作:

- (NSDictionary *)serializedDictionaryWithError:(NSError **)error
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.someProperty forKey:@"some-property"];
    NSDictionary *childDict = [self.childObject serializedDictionaryWithError:error];
    if (childDict == nil) return nil;
    [dict setObject:childDict forKey:@"child-object"];
    return dict;
}

该死!

于 2012-02-08T17:54:49.853 回答