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;

}

上一篇:javascript使用事件委托


下一篇:python字典、字符串(json串)、字节串之间的转化