Friday, January 20, 2012

NSJSONSerialization - Convert NSDictionary to JSON

Since iOS5 Apple offers a very simple way to handle JSON Strings with the NSJSONSerialization Class.
In this post I want to show how easy it is to create a JSON String with NSJSONSerialization.

NSMutableData *myData = [[NSMutableData alloc]init];
NSDictionary *myDictionary = [[NSDictionary alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:myData];
[archiver encodeObject:myDictionary forKey:@"MyKEY"];
[archiver finishEncoding];
id MyJSONObject = [NSJSONSerialization JSONObjectWithData:myData options:0 error:nil];

Please note that I did not put an NSError Object in place to keep the example as simple as possible.

If you still have to support iOS4.X please have a look at Convert NSDictionary to JSON

No comments:

Post a Comment