我有这个NSMutableDictionary,当我尝试运行这个函数来添加数据时,如果有不是字母的字符,它会崩溃返回JSON(例如,如果字符串是(Hello World)那么空格之间的空格两个单词会导致崩溃)除非我用下划线替换它们,如下所示。如何让它接受任何角色?
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
NSString *name = [[NSString alloc] initWithUTF8String:msg];
// If the dictionary has any of these characters within it, code breaks.
NSString *prodNameWithUnderscores = [name stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSString *prodNameWithUnderscores2 = [prodNameWithUnderscores stringByReplacingOccurrencesOfString:@"'" withString:@"_"];
NSString *prodNameWithUnderscores3 = [prodNameWithUnderscores2 stringByReplacingOccurrencesOfString:@"(" withString:@"_"];
NSString *prodNameWithUnderscores4 = [prodNameWithUnderscores3 stringByReplacingOccurrencesOfString:@")" withString:@"_"];
NSString *prodNameWithUnderscores5 = [prodNameWithUnderscores4 stringByReplacingOccurrencesOfString:@"~" withString:@"_"];
NSData *data = [name dataUsingEncoding:NSUTF8StringEncoding];
dict = [NSPropertyListSerialization propertyListWithData:data options:kNilOptions format:NULL error:NULL];**strong text**
return @{ @"name": dict };
答案 0 :(得分:0)
我明白了,我不需要做任何序列化来做JSON的内置转换器。我刚刚传递了正常的字符串。