Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Generate JSON string from NSDictionary in iOS

I have a dictionary I need to generate a JSON string by using dictionary. Is it possible to convert it? Can you guys please help with this?
by

2 Answers

akshay1995
Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.

To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.

Here is how to do it:

NSError error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
pankajshivnani123
To convert a NSDictionary to a NSString:

NSError  err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString
myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Login / Signup to Answer the Question.