Monday, June 20, 2011

Convert NSDictionary to JSON with SBJson

UPDATE: For the iOS5 Solution please look at http://life-of-a-tech-dude.blogspot.com/2012/01/nsjsonserialization-convert-nsstring-to.html

Most people writing software for Apples iOS probably had to read some sort of data from a JSON encoded string and there are heaps of examples out there who explain in every detail how you can DECODE a JSON string using the JSON-Framework (https://github.com/stig/json-framework).

But how about the other way around ??
Let's have a look:

1.) You need the JSON Framework from https://github.com/stig/json-framework installed and added as a framework to your Project. If you don't know how to do that please read the article at http://iphonedevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html

2.) You need to have your data ready as a NSDictionary or NSArray.

3.) Just use following source code and you are done :
"myDictionary" is representing your NSDictionary Object.

#import "JSON.h"
.
.
.
SBJsonWriter *jsonWriter = [SBJsonWriter new];
.
.
.
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
NSLog(jsonString);
.
.
.

All Done

2 comments:

  1. True. I was using a slighter older version where the header file was called JSON.h instead of SBJson.h. I corrected above snippet.

    Thanks for pointing that out.

    ReplyDelete