xcode NSJSONSerialization JSONObjectWithData 返回 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20574376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSJSONSerialization JSONObjectWithData returns NSString
提问by CyberK
I have a NSJSONSerialization JSONObjectWithData where I pass a NSData object. As a result I get a NSString instead of an NSDictionary. The complete line I have is:
我有一个 NSJSONSerialization JSONObjectWithData,我在其中传递了一个 NSData 对象。结果我得到了一个 NSString 而不是一个 NSDictionary。我拥有的完整行是:
NSDictionary* jsonDec = [NSJSONSerialization JSONObjectWithData:jData options:NSJSONReadingAllowFragments error:&error];
And the return is:
回报是:
Why don't I get a NSDictionary back? My backend is PHP on the server...
为什么我没有拿回 NSDictionary?我的后端是服务器上的 PHP ......
Thanks in advance!
提前致谢!
回答by user2828120
NSDictionary *jsonDec;
NSError* error = nil;
jsonDec = [NSJSONSerialization JSONObjectWithData: jData
options: NSJSONReadingMutableContainers
error: &error];
if (error)
{
NSLog(@"Error: %@",error);
}
Apple doc: NSJSONReadingMutableContainers- Specifies that arrays and dictionaries are created as mutable objects.
Apple 文档:NSJSONReadingMutableContainers- 指定将数组和字典创建为可变对象。
回答by LJ Wilson
I use this when consuming JSON
responses (mine usually are arrays of dictionaries). I prefer to use object type id
and just use introspection to determine whether it is an NSArray
or NSDictionary
. BTW - my web requests are either done using AFNetworking (v2) or using the Azure SDK.
我在使用JSON
响应时使用它(我的通常是字典数组)。我更喜欢使用对象类型id
,只是使用自省来确定它是 anNSArray
还是NSDictionary
. 顺便说一句 - 我的网络请求是使用 AFNetworking (v2) 或使用 Azure SDK 完成的。
id jsonDec = [NSJSONSerialization JSONObjectWithData:jData options:0 error:&error];