Anyone have idea how to serialize nested JSON based on NSObject class? There is a discussion to serialize simple JSON here , but it is not generic enough to cater complex nested JSON.
Imagine this is the result of JSON:
{ "accounting" : [{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
],
"sales" : [{ "firstName" : "Sally",
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim",
"lastName" : "Galley",
"age" : 41 }
]}
From this class:
@interface Person : NSObject{}
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *age;
@end
@interface Department : NSObject{}
@property (nonatomic, strong) NSMutableArray *accounting; //contain Person class
@property (nonatomic, strong) NSMutableArray *sales; //contain Person class
@end
How to serialize/deserialize them based on class generically?
EDIT
Currently i'm able to generate payload like this based on any class:
NSMutableDictionary *Payload = [self serialize:objClass];
But it does not cater nested complex JSON. Anyone have better solution for this? This library for C# cater serialize/deserialze based on object class. I want to reproduce something the same based on NSObject
initWithJSONObject:error:(via a category, for example).initWithDictionaryis probably more general. (You can include theerror:parm if it's merited.)initWithDictionaryis a good choice.initWithDictionaryyou don't really need to worry about reading JSON into objects. It pretty much just works -- pass the dictionary to the init routine, it handles what it can, and creates subsidiary objects and calls theirinitWithDictionarymethods in due course. So long as the JSON roughly matches the object structure you're good.