Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
Not satisfied by the Answer? Still have doubts?
Ask Question

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?
string json ios

2 Answers

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

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

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

Login / Signup to Answer the Question.

  • Be descriptive with your answer, and try to avoid copy-pasting external links, instead guide the user who has asked the question, where can they find the detailed answer.
  • You cannot share any URL in answer.
  • To make a text bold, surround the text with single asterisk, for example *bold text*
  • To format a text like code, surround the text within double asterisk, for example **code**
  • To add a multiline piece of code, surround the whole code within triple asterisk, for example *** multiline code ***
  • Please verify before submitting the answer.