Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing complex NSObject to JSON pattern

Tags:

json

ios

jsonkit

I have a series of NSObject's I would like to serialize to JSON and post to a service. The final object consists of several levels of these NSObject subclasses nested within each other.

Each one of these objects follows a protocol with a method which returns that objects properties in an NSDictionary with the appropriate keys. However, some of these properties are other objects and so forth, making the serialization a bit complicated.

Is there a pattern I could use to simplify serializing the final object? Using JSONKit, it seems I would need to serialize each dictionary individually from the deepest object and work backwards, checking for errors, then adding to a compound string. I know this can not possibly be the best method using this very capable library. Any suggestion or guidance is welcomed.

Edit 1

JSONKit GitHub URL

JSONKit Readme Documentation

like image 902
Oh Danny Boy Avatar asked Aug 02 '26 01:08

Oh Danny Boy


2 Answers

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)

like image 131
Nick Lockwood Avatar answered Aug 04 '26 16:08

Nick Lockwood


Now you can solve this problem easily using JSONModel. JSONModel is a library that generically serialize/deserialize your object based on Class. You can even use non-nsobject based for property like int, short and float. It can also cater nested-complex JSON. It handles error checking for you.

Given this JSON {"firstname":"Jenson","surname":"Button"}

Deserialize example. in header file:

#import "JSONModel.h"

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

in implementation file:

#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):
}

Serialize Example. In implementation file:

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

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

NSLog(@"%@", [person toJSONString]);
like image 43
X Sham Avatar answered Aug 04 '26 14:08

X Sham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!