iOS中對(duì)JSON的操作通常的使用場(chǎng)景是string與object相互轉(zhuǎn)化齿坷,NSJSONSerialization類就是用于這個(gè)場(chǎng)景的桂肌,只不過是data與object相互轉(zhuǎn)化,我們可以更進(jìn)一步做data和string相互轉(zhuǎn)化永淌。
首先JSON Ojbect的標(biāo)準(zhǔn)是什么崎场?先看看NSJSONSerialization里
+ (BOOL)isValidJSONObject:(id)obj
的使用說明:
/* Returns YES if the given object can be converted to JSON data,
NO otherwise. The object must have the following properties:
- Top level object is an NSArray or NSDictionary
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- All dictionary keys are NSStrings
- NSNumbers are not NaN or infinity
Other rules may apply. Calling this method or attempting a conversion
are the definitive ways to tell
if a given object can be converted to JSON data.
*/
+ (BOOL)isValidJSONObject:(id)obj;
因此我們可以很放心的使用這個(gè)方法判斷是否是JSON object了
JSON data與JSON object互轉(zhuǎn),通常只用這兩個(gè)方法:
+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
先看看JSON string -> JSON object (dictionary 或 array)
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:nil];
然后是JSON object -> JSON string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:stringData
encoding:NSUTF8StringEncoding];
以上代碼可以看出遂蛀,中間都是經(jīng)過NSData的(base64也是這樣)照雁。這樣寫并沒有安全保護(hù),而且不方便使用答恶。所以需要封裝一下饺蚊。
首先創(chuàng)建一個(gè)NSObject的分類
#import <Foundation/Foundation.h>
@interface NSObject (ZZJSONExt)
- (NSString *)JSONString;
- (id)JSONObject;
@end
@implementation NSObject (ZZJSONExt)
- (NSString *)JSONString {
// 請(qǐng)先判斷自己是不是合法的JSON類型,不是就不能玩
if ([NSJSONSerialization isValidJSONObject:self]) {
NSData *stringData = [NSJSONSerialization dataWithJSONObject:self
options:NSJSONWritingPrettyPrinted
error:nil];
return [[NSString alloc] initWithData:stringData
encoding:NSUTF8StringEncoding];
} else if ([self isKindOfClass:[NSString class]]) {
// 這情況很坑悬嗓,自己是string但又不知道是不是jsonString
return [[self JSONObject] JSONString];
}
return nil;
}
- (id)JSONObject {
// 請(qǐng)先判斷自己是不是合法的JSON類型污呼,是就別湊熱鬧了
if ([NSJSONSerialization isValidJSONObject:self]) {
return self;
}
id myself = self;
NSData *jsonData = nil; // 萬物基于data
if ([self isKindOfClass:[NSData class]]) {
// 自己是data的話直接轉(zhuǎn)JSON
jsonData = myself;
} else if ([self isKindOfClass:[NSString class]]) {
// 是string的話先轉(zhuǎn)dat再轉(zhuǎn)JSON
jsonData = [myself dataUsingEncoding:NSUTF8StringEncoding];
}
if (jsonData) {
return [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:nil];
}
return nil;
}
@end
然后可以隨便轉(zhuǎn)來轉(zhuǎn)去啦
/* 任何object都可以用,是json就有結(jié)果 */
[xxx JSONString];
[yyy JSONObject];
/* 完 */