首页 > 学院 > 开发设计 > 正文

NSArray、NSDictionary转成JSONString

2019-11-14 19:12:31
字体:
来源:转载
供稿:网友

1.NSArray转换成JSONString

 //NSArray+JSONString.h@interface NSArray (JSONString)- (NSString *)jsonStringWithPRettyPrint:(BOOL)prettyPrint;@end
@implementation NSArray (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

2.NSDictionary 转成 JSONString

 //NSDictionary+JSONString.h@interface NSDictionary (JSONString)-(NSString*) jsonStringWithPrettyPrint:(BOOL) prettyPrint;@end
//NSDictionary+JSONString.m@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

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表