Serialize and Deserialize Objective-C objects into JSON Serialize and Deserialize Objective-C objects into JSON json json

Serialize and Deserialize Objective-C objects into JSON


Finally we can solve this problem easily using JSONModel. This is the best method so far. 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.

Considering this JSON example:

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

1) Deserialize example. in header file:

#import "JSONModel.h"@interface Person : JSONModel @property (nonatomic, strong) NSString *firstName;@property (nonatomic, strong) NSString *lastName;@property (nonatomic, strong) NSNumber *age;@end@protocol Person;@interface Department : JSONModel@property (nonatomic, strong) NSMutableArray<Person> *accounting;@property (nonatomic, strong) NSMutableArray<Person> *sales;@end

in implementation file:

#import "JSONModelLib.h"#import "myJSONClass.h"NSString *responseJSON = /*from example*/;Department *department = [[Department alloc] initWithString:responseJSON error:&err];if (!err){    for (Person *person in department.accounting) {        NSLog(@"%@", person.firstName);        NSLog(@"%@", person.lastName);        NSLog(@"%@", person.age);             }    for (Person *person in department.sales) {        NSLog(@"%@", person.firstName);        NSLog(@"%@", person.lastName);        NSLog(@"%@", person.age);             }}

2) Serialize Example. In implementation file:

#import "JSONModelLib.h"#import "myJSONClass.h"Department *department = [[Department alloc] init];Person *personAcc1 = [[Person alloc] init];personAcc1.firstName = @"Uee";personAcc1.lastName = @"Bae";personAcc1.age = [NSNumber numberWithInt:22];[department.accounting addOject:personAcc1];Person *personSales1 = [[Person alloc] init];personSales1.firstName = @"Sara";personSales1.lastName = @"Jung";personSales1.age = [NSNumber numberWithInt:20];[department.sales addOject:personSales1];NSLog(@"%@", [department toJSONString]);

And this is NSLog result from Serialize example:

{ "accounting" : [{ "firstName" : "Uee",                      "lastName"  : "Bae",                    "age"       : 22 }                 ],                              "sales"      : [{ "firstName" : "Sara",                     "lastName"  : "Jung",                    "age"       : 20 }                  ]}


It sounds like you're looking for a serialization library that can let you convert objects of your own custom classes into JSON, and then reconstitute them back. Serialization of property-list types (NSArray, NSNumber, etc.) already exists in 3rd party libraries, and is even built into OS X 10.7 and iOS 5.

So, I think the answer is basically "no". I asked this exact question a month or two ago on the cocoa-dev mailing list, and the closest I got to a hit was from Mike Abdullah, pointing to an experimental library he'd written:

https://github.com/mikeabdullah/KSPropertyListEncoder

This archives objects to in-memory property lists, but as I said there are already APIs for converting those into JSON.

There's also a commercial app called Objectify that claims to be able to do something similar:

http://tigerbears.com/objectify/

It's possible I'll end up implementing what you're asking for as part of my CouchCocoa library, but I haven't dived into that task yet.

https://github.com/couchbaselabs/CouchCocoa


You can easily add JSON capability to NSObject class with the help of NSDictionary,NSArray and NSJSONSerialization

Serialization:

Just see the example it will be very easy to understand.

Adding JSON Capability to NSObject Class:-

@interface JsonClassEmp : NSObject@property(strong,nonatomic)NSString *EmpName,*EmpCode;-(NSDictionary*)GetJsonDict;@end@implementation JsonClassEmp@synthesize EmpName,EmpCode;//Add all the properties of the class in it.-(NSDictionary*)GetJsonDict{    return [NSDictionary dictionaryWithObjectsAndKeys:EmpName,@"EmpName",EmpCode,@"EmpCode", nil];}@end

JSON String Generator:-

In iOS 5, Apple introduced NSJSONSerialization, for parsing JSON strings so by using that we will generate JSON string.

-(NSString*)GetJSON:(id)object{    NSError *writeError = nil;    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&writeError];    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];    return jsonString;}

Moving towards Appleā€™s implementation is always safer to use since you have the guarantee that it will be maintained and kept up to date.

Way to use:-

- (void)viewDidLoad{    [super viewDidLoad];    JsonClassEmp *emp1=[[JsonClassEmp alloc]init];    [emp1 setEmpName:@"Name1"];    [emp1 setEmpCode:@"1"];    JsonClassEmp *emp2=[[JsonClassEmp alloc]init];    [emp2 setEmpName:@"Name2"];    [emp2 setEmpCode:@"2"];    //Add the NSDictionaries of the instances in NSArray    NSArray *arrEmps_Json=@[emp1.GetJsonDict,emp2.GetJsonDict];    NSLog(@"JSON Output: %@", [self GetJSON:arrEmps_Json]);}

Reference

Deserialization:

It's usual way of getting the deserialized data into NSDictionary or NSArray then assign it to class properties.

I am sure using the methods and ideas used above you can serialize & deserialize complex json easily.