gpt4 book ai didi

ios - 在 iOS 中从 NSDictionary 生成 JSON 字符串

转载 作者:bug小助手 更新时间:2023-10-28 01:25:52 26 4
gpt4 key购买 nike

我有一个 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];
}

关于ios - 在 iOS 中从 NSDictionary 生成 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6368867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com