在iOS 5 中,苹果引入了一个解析JSON串的NSJSONSerialization类。
// 将字典或者数组转化为JSON串
- (NSData *)toJSONData:(id)theData{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
options:NSJSONWritingPrettyPrinted
error:&error];
if ([jsonData length] > 0 && error == nil){
return jsonData;
}else{
return nil;
}
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
[jsonString dataUsingEncoding:NSASCIIStringEncoding];
// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:&error];
if (jsonObject != nil && error == nil){
return jsonObject;
}else{
// 解析错误
return nil;
}
}
#import "NSString+JSONCategories.h"
@implementation NSString(JSONCategories)
-(id)JSONValue;
{
NSData* data = [self dataUsingEncoding:NSUTF8StringEncoding];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
#import "NSObject+JSONCategories.h"
@implementation NSObject (JSONCategories)
-(NSData*)JSONString;
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end