iOS開發之將字典、數組轉為JSON字符串方法
//將字典轉換成json格式字符串,不含\n這些符號
+ (NSString *)gs_jsonStringCompactFormatForDictionary:(NSDictionary *)dicJson {
if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {
return nil;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return strJson;
}
//將數組轉換成json格式字符串,不含\n這些符號
+ (NSString *)gs_jsonStringCompactFormatForNSArray:(NSArray *)arrJson {
if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {
return nil;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];
NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return strJson;
}
//將字典轉換成json格式字符串,含\n這些符號,便於閱讀
+ (NSString *)gs_jsonStringPrettyPrintedFormatForDictionary:(NSDictionary *)dicJson {
if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {
return nil;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:NSJSONWritingPrettyPrinted error:nil];
NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return strJson;
}
iOS開發之將字典、數組轉為JSON字符串方法