一、将NSDictionary或NSArray转化为JSON串
// 将字典或者数组转化为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;
}
}
使用这个方法的返回,我们就可以得到想要的JSON串
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
二、将JSON串转化为NSDictionary或NSArray
将NSString转化为NSData
[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;
}
}
三、将JSON串与NSArray和NSDictionary的操作进行封装
当然,也有很多时候,我们将这些操作,分别定义在NSObject和NSString的一个分类中
直接贴:
1.将NSString转化为NSArray或者NSDictionary
#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
2.将NSArray或者NSDictionary转化为NSString
#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
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn