1. 程式人生 > >iOS json轉json字串 不帶空格換行符

iOS json轉json字串 不帶空格換行符

1.第一種方式直接採用拼接方式,例:

-(NSString *)convertToJsonStr
{
 int random=arc4random_uniform(100000);
 NSString *nonce = [NSString stringWithFormat:@"%d",random];
 NSString *sign = [NSString stringWithFormat:@"%@%@%@%@%lld",[self getToken],[self getArea],nonce,[self getClient],[KQDateJS httpTimeCut]];
//拼接json字串、
NSString
*signInfo = [NSString stringWithFormat:@"{\"Token\":\"%@\",\"Area\":\"%@\",\"Nonce\":\"%d\",\"Time\":\"%lld\",\"Client\":\"%@\",\"Sign\":\"%@\"}",[self getToken],[self getArea],random,[KQDateJS httpTimeCut],[self getClient],sign]; return signInfo; }

2.第二種採用NSJSONSerialization提供的方法json轉json字串

-(NSString
*)convertToJsonData:(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; }

通過以上2種方法轉的json字串是不帶空格和換行符的。