iOS NSDictionary转json / 字典转json
iOS 2019-10-17 19:35:31

1、示例一:

     JMSGUser *fromUser = [message fromUser];

    NSDictionary *fromUserDict = @{@"username": [NSString stringWithFormat:@"%@", fromUser.username],

                               @"nickname":[NSString stringWithFormat:@"%@",fromUser.nickname],

                               @"signature":[NSString stringWithFormat:@"%@",fromUser.signature],

                                    @"avatar":[NSString stringWithFormat:@"%@",fromUser.avatar]};

    NSData *jsonData=[NSJSONSerialization dataWithJSONObject:fromUserDict options:NSJSONWritingPrettyPrinted error:nil];

    

    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    

    NSMutableString *fromUserStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [fromUserStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,fromUserStr.length};

    //去掉字符串中的换行符

    [fromUserStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    NSLog(@"jsonStr==%@",fromUserStr);

 

 2、示例二:

C/C++ Code复制内容到剪贴板
  1. NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];  
  2. [dictionary setValue:@"hello" forKey:@"one"];  
  3.   
  4. [dictionary setValue:@"world" forKey:@"two"];  
  5.   
  6. [dictionary setValue:arry forKey:@"three"];  
  7.   
  8. NSData *data=[NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];  
  9.   
  10. NSString *jsonStr=[[NSString alloc]initWithData:datae coding:NSUTF8StringEncoding];  
  11.   
  12. NSLog(@"jsonStr==%@",jsonStr);  

 

 

输出结果为:

 

str=={

"one" : "hello",

"two" : "world",

"three" : [

"001",

"002",

"003"

]

}

本文来自于:http://www.yoyo88.cn/study/swift/463.html

Powered by yoyo苏ICP备15045725号