ios - 获取 NSDictionary 形式的服务器 JSON 响应

标签 ios objective-c json nsdictionary nscfstring

我正在尝试将服务器响应 NSData 获取到 NSDictionary 中,但它返回以下 NSCFString

NSError *error;
NSDictionary* jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

并且无法使用objectForKey访问数据。 给我一种方法来获取此响应作为 NSDictionary 或转换机制。无法通过 kNilOptions 获取任何 NSJSONSerialization 返回 nil

最佳答案

根据这个问题,无法使用带有选项kNilOptionsNSJSONSerialization进行序列化。

所以首先我们需要将上面的序列化 JSON 作为 NSString 获取,然后再次将其转换为 NSData。然后,您可以使用 kNilOptions 将其转换回 NSDictionary

NSString* jsonString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonDictionary = [NSJSONSerialization jsonData options:0 error:nil];

关于ios - 获取 NSDictionary 形式的服务器 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56421632/

相关文章:

ios - 从值中获取数字的最短方法

iOS:将手势传递给下面的 View

iphone - CLLocation 导致 EXC_BAD_ACCESS

javascript - 如何从 JSON 值中选取数据

iphone - 当 UIView 在窗口中的位置发生变化时是否有通知?

ios - 如何在按钮点击时实现 segue?

ios - 在 UIButton IOS 上创建一系列动画

ios - 迁移 UIViewController 的 UITableView 元素

javascript - forEach 中的 If/Else 仅添加段落而不添加标题,但在本地它正在工作(React 和 Editor.js)

javascript - 将 JS 数组转换为对象