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?
14 Answers
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
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];
}
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.
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);
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];
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
}
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.
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)
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()
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)")
}
}
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