下面是NSArray和NSDicary的分類,以使這一過程變得非常簡單。我添加了一個漂亮打印選項(換行符和制表符,以便于閱讀)。
@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