我有一个 dictionary
我需要使用 dictionary
生成一个 JSON 字符串
。是否可以转换它?各位大神能帮忙解决一下吗?
Apple 在 iOS 5.0 和 Mac OS X 10.7 中添加了 JSON 解析器和序列化器。见 NSJSONSerialization .
要从 NSDictionary 或 NSArray 生成 JSON 字符串,您不再需要导入任何第三方框架。
这是怎么做的:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
我是一名优秀的程序员,十分优秀!