I need to serialize and deserialize objective-c objects into JSON to store in CouchDB. Do people have any example code for best practice for a general solution? I looked a
Did you mean this? ;)
http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946
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
I have a simple model class, which I wanted to turn into a JSON-Object.
For this purpose I added a „jsonData“-method to my model class: The method turns the model properties into foundation objects (int numbers into NSNumber objects etc.) Then a dictionary is populated with these objects and the corresponding keys (also the later JSON keys). After an (optional) check for validity, the JSON data object ist created with the NSJSONSerialization class „dataWithJSONObject“ method and returned.
- (NSData *)jsonData {
NSDictionary *root = @{@"Sport" : @(_sportID), // I´m using literals here for brevity’s sake
@"Skill" : @(_skillLevel),
@"Visibility" : @(_visibility),
@"NotificationRange" : @(_notificationRange)};
if ([NSJSONSerialization isValidJSONObject:root]) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:root
options:0
error:nil];
return jsonData;
}
return nil;
}
This is possible using the RestKit library's object mapping system.
http://restkit.org/
You can easily add JSON capability to NSObject class with the help of NSDictionary,NSArray and NSJSONSerialization
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
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.
You may want to try JTObjectMapping. Their description:
JTObjectMapping - Inspired by RestKit. A very simple objective-c framework that maps a JSON response from NSDictionary or NSArray to NSObject subclasses for iOS.
It's very small (unlike RestKit) and works great.