Detailed example of dictionary to string developed by IOS

Time:2021-9-25

Detailed example of dictionary to string developed by IOS

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

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

Idea: just use the system JSON serialization class, and nsdata is used as the intermediate bridge

    // 1. Convert the dictionary into a string (JSON format) and use 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 a string object with nsdata


NSString *dicStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 
Nslog (@ "dictionary converted 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 for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!