标签:str keyword lin contain new convert return ati ons
+ (NSString*)convertToJSONData:(id)infoDict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don‘t care about the readability of the generated string
error:&error];
NSString *jsonString = @"";
if (! jsonData)
{
NSLog(@"Got an error: %@", error);
}else
{
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
[jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
return jsonString;
}
+ (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;
}
iOS开发--字典(NSDictionary)和JSON字符串(NSString)之间互转
标签:str keyword lin contain new convert return ati ons
原文地址:http://www.cnblogs.com/ming1025/p/6186171.html