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、示例二:
- NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
- [dictionary setValue:@"hello" forKey:@"one"];
- [dictionary setValue:@"world" forKey:@"two"];
- [dictionary setValue:arry forKey:@"three"];
- NSData *data=[NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
- NSString *jsonStr=[[NSString alloc]initWithData:datae coding:NSUTF8StringEncoding];
- NSLog(@"jsonStr==%@",jsonStr);
输出结果为:
str=={
"one" : "hello",
"two" : "world",
"three" : [
"001",
"002",
"003"
]
}