p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Menlo; color: #929292 }
span.s1 { }
NSDictionary (JSON).h文件
#import <Foundation/Foundation.h> @interface NSDictionary (JSON) /** * 转换成JSON串字符串(没有可读性) * * @return JSON字符串 */ - (NSString *)toJSONString; /** * 转换成JSON串字符串(有可读性) * * @return JSON字符串 */ - (NSString *)toReadableJSONString; /** * 转换成JSON数据 * * @return JSON数据 */ - (NSData *)toJSONData; @end
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Menlo; color: #929292 }
span.s1 { }
NSDictionary (JSON).m文件
#import "NSDictionary+JSON.h" @implementation NSDictionary (JSON) - (NSString *)toJSONString { NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:nil]; if (data == nil) { return nil; } NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return string; } - (NSString *)toReadableJSONString { NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil]; if (data == nil) { return nil; } NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return string; } - (NSData *)toJSONData { NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil]; return data; } @end
时间: 2024-10-10 10:35:33