簡述
iOS 5 中,蘋果引入了一個(gè)解析JSON串的NSJSONSerialization類灶伊。
通過該類疆前,我們可以完成JSON數(shù)據(jù)與NSDictionary和NSArray之間的轉(zhuǎn)化。不需要另外使用第三方庫聘萨。
一竹椒、NSDictionary或NSArray轉(zhuǎn)化為JSON串
// 將字典或者數(shù)組轉(zhuǎn)化為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;
}
//使用這個(gè)方法的返回,我們就可以得到想要的JSON串
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
}
序列化函數(shù)的說明
- 先看這段代碼
/* Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.*/
+(nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
- 此方法在Objective-C中用來從對象生成JSON米辐,其中類型NSJSONWritingOptions蘋果描述為”O(jiān)ptions for writing JSON data.”胸完,官方的說明是設(shè)置NSJSONWritingOptions 會(huì)提高閱讀性,不設(shè)置的話就會(huì)得到我們想要的格式翘贮,但是我們看到這里赊窥,只有一個(gè)枚舉:
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
NSJSONWritingPrettyPrinted = (1UL << 0)
} NS_ENUM_AVAILABLE(10_7, 5_0);
二、JSON串轉(zhuǎn)化為NSDictionary或NSArray
//將NSString轉(zhuǎn)化為NSData
[jsonString dataUsingEncoding:NSASCIIStringEncoding];
// 將JSON串轉(zhuǎn)化為字典或者數(shù)組
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:&error];
if (jsonObject != nil && error == nil){
return jsonObject;
}else{
// 解析錯(cuò)誤
return nil;
}
}
三狸页、將JSON串與NSArray和NSDictionary的操作進(jìn)行封裝
當(dāng)然锨能,也有很多時(shí)候,我們將這些操作芍耘,分別定義在NSObject和NSString的一個(gè)分類中
直接貼:
1.將NSString轉(zhuǎn)化為NSArray或者NSDictionary
#import "NSString+JSONCategories.h" // ------ 其實(shí)可以不用category
@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轉(zhuǎn)化為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