首先給大家?guī)?lái)網(wǎng)上常見(jiàn)的Json字符串轉(zhuǎn)字典,字典轉(zhuǎn)Json字符串代碼
Json字符串轉(zhuǎn)字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err)
{
NSLog(@"json解析失敳吵睢:%@",err);
return nil;
}
return dic;
}
字典轉(zhuǎn)Json字符串
+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
有時(shí)候我們需要的把字典轉(zhuǎn)成Json字符串(去掉空格檐什、換行符等)瞳收、我們一般的做法
+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的換行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
return mutStr;
}
這種做法看似解決了、Json字符串里面的空格厢汹、換行符,實(shí)際上把鍵值對(duì)里面的key
,value
的空格也去掉
其實(shí)iOS11
已經(jīng)存在對(duì)應(yīng)的枚舉類(lèi)型谐宙,把字典轉(zhuǎn)換成單行Json字符串的data
下面我們就介紹次枚舉
NSJSONWritingOptions
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
NSJSONWritingPrettyPrinted = (1UL << 0),
/* Sorts dictionary keys for output using [NSLocale systemLocale]. Keys are compared using NSNumericSearch. The specific sorting method used is subject to change.
*/
NSJSONWritingSortedKeys API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) = (1UL << 1)
} API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
對(duì)上面字段的解釋:
NSJSONWritingPrettyPrinted = (1UL << 0) //是將生成的json數(shù)據(jù)格式化輸出烫葬,這樣可讀性高
NSJSONWritingSortedKeys //輸出的json字符串就是一整行
注意 不設(shè)置則輸出的json字符串就是一整行。
最后我們改上面字典轉(zhuǎn)Json字符串
的代碼為下面代碼:
+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
NSError *error;
// 注
//NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingSortedKeys error:&error];
// NSJSONWritingSortedKeys這個(gè)枚舉類(lèi)型只適用iOS11所以我是使用下面寫(xiě)法解決的
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:nil error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
這樣我們得到的Json字符串就是一行沒(méi)有空格和換行符的字符串
如果有更好的方法凡蜻、不吝賜教搭综!