Objective-C: How to convert a dictionary to JSON string?

Akarsh Seggemu
1 min readJun 25, 2022

Dictionary is used to key and value associations. For data-interchange, JSON is a preferred format.

When developing using Objective-C, if you have data stored in a dictionary and it needs to be interchanged, then one of the way to do it is converting the dictionary into a JSON string.

Here is an example on how to convert dictionary into JSON string,

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Akarsh", @"name", nil];

NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"Value of json string %@", jsonString);

return 0;
}

output:

Value of json string {

"name": "Akarsh"

}

In the above code, a dictionary is created using key name and value Akarsh. The dictionary is converted into a NSMutableDictionary object into a JSON object and stored in data. The options parameter NSJSONWritingPrettyPrinted makes the JSONS object more readable. The jsonString stores the converted data using UTF-8 code units encoding.

For more information, refer to

I hope my article helps you understand how to convert a dictionary to JSON string in Objective-C.

If you like my articles, please follow me. You can also support me by buying me a coffee.

--

--

Akarsh Seggemu

IT Team Lead | MSc in Computer Science from Technische Universität Berlin | Writing articles to Empower Software Engineers and IT Leaders