SoFunction
Updated on 2025-04-12

Detailed explanation of the example of dictionary to string in IOS development

Detailed explanation of the example of dictionary to string in IOS development

In actual development requirements, sometimes we need to package certain objects and finally splice them into parameters

For example, we package all parameter dictionaries into a string and splice them into the parameters

Idea: Use the system JSON serialization class, NSData as the intermediate bridge

//1. Convert the dictionary to string (JSON format), using NSData as a bridge;

NSDictionary *dic = @{@"name":@"Lisi",@"sex":@"m",@"tel":@"1770"}; 

//Convert string to NSData

  
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; 

//Create string object with NSData

NSString *dicStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 
NSLog(@"Dictionary conversion to string is %@",dicStr); 

The result is a JSON string:

{ 
 "name" : "Lisi", 
 "sex" : "m", 
 "tel" : "1770" 
} 


If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!