字典序列化Json
NSDictionary+BVJSONString.h
#import <Foundation/Foundation.h>
@interface NSDictionary (BVJSONString)
- (NSString*)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
NSDictionary+BVJSONString.m
#import "NSDictionary+BVJSONString.h"
@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(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
数组序列化Json
NSArray+BVJSONString.h
#import <Foundation/Foundation.h>
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
NSArray+BVJSONString.m
#import "NSArray+BVJSONString.h"
@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(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
prettyPrint是方便打印查看,如果需要�使用的话还是设为NO,不然可能会出现一些你不需要的问题。
网友评论