IOS: converts JSON strings to dictionaries, dictionaries to JSON strings, and iosjson
In iOS development and server interaction, dictionary and JSON format strings are often used to convert each other.
The Code is as follows:
1. Convert strings into dictionaries in JSON format
+ (NSDictionary *) dictionaryWithJsonString :( NSString *) jsonString {if (jsonString = nil) {return nil;} NSData * jsonData = [jsonString dataUsingEncoding: encoding]; NSError * err; NSDictionary * dic = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: & err]; if (err) {NSLog (@ "JSON parsing failed: % @", err ); return nil;} return dic ;}
2. Convert dictionaries to strings in JSON format
+ (NSString*)dictionaryToJson:(NSDictionary *)dic{ NSError *parseError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; }