Skip to content

Instantly share code, notes, and snippets.

@ThinhPhan
Created April 26, 2015 18:40
Show Gist options
  • Save ThinhPhan/702b1766ee60903506dd to your computer and use it in GitHub Desktop.
Save ThinhPhan/702b1766ee60903506dd to your computer and use it in GitHub Desktop.
Category for get JSON string from NSDictionary, and NSData.
//
// NSArray+JSONString.h
//
//
// Created by Thinh Phan on 4/26/15.
// Copyright (c) 2015 Gennova. All rights reserved.
//
@interface NSArray (JSONString)
- (NSString *) jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
//
// NSArray+JSONString.m
//
//
// Created by Thinh Phan on 4/26/15.
// Copyright (c) 2015 Gennova. All rights reserved.
//
@implementation NSArray (JSONString)
- (NSString*) jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
//
// NSDictionary+JSONString.h
//
//
// Created by Thinh Phan on 4/26/15.
// Copyright (c) 2015 Gennova. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (JSONString)
- (NSString*) jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
//
// NSDictionary+JSONString.m
//
//
// Created by Thinh Phan on 4/26/15.
// Copyright (c) 2015 Gennova. All rights reserved.
//
#import "NSDictionary+JSONString.h"
@implementation NSDictionary (JSONString)
- (NSString*) jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment