358

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 on this?

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
Sekhar Bhetalam
  • 4,501
  • 6
  • 33
  • 52

14 Answers14

775

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];
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Guillaume
  • 21,685
  • 6
  • 63
  • 95
  • 88
    This is good advice...it's really annoying to have projects have a ton of third party libraries. – zakdances Aug 09 '12 at 06:54
  • 1
    +1 Adding this as a category to `NSArray` and `NSDictionary` would make reusing it much simpler. – devios1 Nov 15 '13 at 21:41
  • how to convert the json back to dictionary? – OMGPOP Mar 08 '14 at 07:06
  • 5
    @OMGPOP - `[NSJSONSerialization JSONObjectWithData:options:error:]` returns a Foundation objec from given JSON data – Lukasz 'Severiaan' Grela Apr 15 '14 at 10:39
  • Successfully converted to JSON format but I'm getting this error `*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write' *** First throw call stack:` – Dayanithi Natarajan Apr 20 '17 at 14:31
  • This not make escape string for special characters like & (ampersand). for example: output is like & instead of \& – Sabrina May 30 '22 at 14:01
241

Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end

.

@implementation NSDictionary (BVJSONString)

  -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
     NSError *error;
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                     error:&error];

     if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"{}";
     } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     } 
 }
@end

.

@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end

.

@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"[]";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}
@end
Itachi
  • 5,777
  • 2
  • 37
  • 69
Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
  • 8
    if we create a category of NSObject and put the same method, it works for both NSArray and NSDictionary. No need to write two separate files/interfaces. And it should return nil in case of error. – Abdullah Umer Jul 14 '14 at 04:55
  • Why do you assume that `NSUTF8StringEncoding` is the correct encoding? – Heath Borders Apr 08 '15 at 02:29
  • 5
    Nevermind, the documentation says "The resulting data is a encoded in UTF-8." – Heath Borders Apr 08 '15 at 02:30
  • @AbdullahUmer That's what I've done too as I presume it'll also work on `NSNumber`, `NSString`, and `NSNull` – will find out in a minute or two! – Benjohn Feb 07 '17 at 13:18
67

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];
jobima
  • 5,790
  • 1
  • 20
  • 18
34

NOTE: This answer was given before iOS 5 was released.

Get the json-framework and do this:

#import "SBJsonWriter.h"

...

SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];

NSString *jsonString = [jsonWriter stringWithObject:myDictionary];  

[jsonWriter release];

myDictionary will be your dictionary.

Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
  • Thanks for your response. Can you please suggest me how to add the framework to my application, looks like there are so many folder in the stig-json-framework-36b738f – Sekhar Bhetalam Jun 16 '11 at 09:08
  • @ChandraSekhar after cloning the git repository, it should suffice to add the Classes/ folder to your project. – Nick Weaver Jun 16 '11 at 11:15
  • 1
    I just wrote http://stackoverflow.com/questions/11765037/sbjsonwriter-nested-nsdictionary/12383548#12383548 to fully illustrate this. Include error checking and some pieces of advise. – Pascal Sep 12 '12 at 08:05
27

You can also do this on-the-fly by entering the following into the debugger

po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
Andy
  • 14,260
  • 4
  • 43
  • 56
16

You can pass array or dictionary. Here, I am taking NSMutableDictionary.

NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];

To generate a JSON string from a NSDictionary or NSArray, You don't need to import any third party framework. Just use following code:-

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary
                    options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                    error:&error];
NSString *jsonString;
if (jsonData) {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //This is your JSON String
    //NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
    NSLog(@"Got an error: %@", error);
    jsonString = @"";
}
NSLog(@"Your JSON String is %@", jsonString);
Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
12
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
        [contentDictionary setValue:@"a" forKey:@"b"];
        [contentDictionary setValue:@"c" forKey:@"d"];
        NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:data
                                                  encoding:NSUTF8StringEncoding];
Robert
  • 431
  • 7
  • 19
user2885077
  • 702
  • 6
  • 14
  • When I pass this to POST request as a parameter, I'm recieveing `+[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'` error. Using XCode 9.0 – Dayanithi Natarajan Oct 13 '17 at 10:36
7

In Swift (version 2.0):

class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
    let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)

    var jsonStr: String?
    if data != nil {
        jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
    }

    return jsonStr
}
King-Wizard
  • 15,628
  • 6
  • 82
  • 76
3

Now no need third party classes ios 5 introduced Nsjsonserialization

NSString *urlString=@"Your url";
NSString *urlUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[[NSURL alloc]initWithString:urlUTF8];
NSURLRequest *request=[NSURLRequest requestWithURL:url];

NSURLResponse *response;

NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSError *myError = nil;

NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:&myError];

Nslog(@"%@",res);

this code can useful for getting jsondata.

talegna
  • 2,407
  • 2
  • 19
  • 22
mahesh chowdary
  • 432
  • 5
  • 13
3

Here is the Swift 4 version

extension NSDictionary{

func toString() throws -> String? {
    do {
        let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        return String(data: data, encoding: .utf8)
    }
    catch (let error){
        throw error
    }
}

}

Usage Example

do{
    let jsonString = try dic.toString()
    }
    catch( let error){
        print(error.localizedDescription)
    }

Or if you are sure it is valid dictionary then you can use

let jsonString = try? dic.toString()
levin varghese
  • 810
  • 12
  • 12
  • 1
    This wont perform like the requested question, prettyPrint retains the spacing when attempting to squash into a string. – Sean Lintern Dec 07 '18 at 11:24
  • let data = try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed) – Vivek Jan 06 '22 at 11:39
3

This will work in swift4 and swift5.

let dataDict = "the dictionary you want to convert in jsonString" 

let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)

let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

print(jsonString)
brass monkey
  • 5,841
  • 10
  • 36
  • 61
azeem usmani
  • 517
  • 4
  • 9
1

As of ISO7 at least you can easily do this with NSJSONSerialization.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Jeef
  • 26,861
  • 21
  • 78
  • 156
1

In Swift, I've created the following helper function:

class func nsobjectToJSON(swiftObject: NSObject) {
    var jsonCreationError: NSError?
    let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)!

    if jsonCreationError != nil {
        println("Errors: \(jsonCreationError)")
    }
    else {
        // everything is fine and we have our json stored as an NSData object. We can convert into NSString
        let strJSON : NSString =  NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
        println("\(strJSON)")
    }
}
James Laurenstin
  • 506
  • 1
  • 6
  • 13
-1
public func jsonPrint(_ o: NSObject, spacing: String = "", after: String = "", before: String = "") {
    let newSpacing = spacing + "    "
    if o.isArray() {
        print(before + "[")
        if let a = o as? Array<NSObject> {
            for object in a {
                jsonPrint(object, spacing: newSpacing, after: object == a.last! ? "" : ",", before: newSpacing)
            }
        }
        print(spacing + "]" + after)
    } else {
        if o.isDictionary() {
            print(before + "{")
            if let a = o as? Dictionary<NSObject, NSObject> {
                for (key, val) in a {
                    jsonPrint(val, spacing: newSpacing, after: ",", before: newSpacing + key.description + " = ")
                }
            }
            print(spacing + "}" + after)
        } else {
            print(before + o.description + after)
        }
    }
}

This one is pretty close to original Objective-C print style

markov
  • 219
  • 1
  • 7