iOS5.0之后,系统自带生成json数据的方法,但是今天遇到的问题是需要把里面的空格和回车全部去掉.这样生成的json字符串和第三方库如:SBJson,JsonKit,TouchJson等生成的一样,并且在Json中如果字典的value是double类型保留小数位会成功.而第三方库会失败.
//数据转成JsonString类型
-(NSString*)ObjectTojsonString:(id)object
{
NSString *jsonString = [[NSStringalloc]init];
NSError *error;
NSData *jsonData = [NSJSONSerializationdataWithJSONObject:object
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(@"error: %@", error);
} else {
jsonString = [[NSStringalloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableStringstringWithString: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;
}