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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:25:59  来源:igfitidea点击:

NSJSONSerialization JSONObjectWithData returns NSString

iosxcode

提问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:

回报是:

enter image description here

在此处输入图片说明

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 JSONresponses (mine usually are arrays of dictionaries). I prefer to use object type idand just use introspection to determine whether it is an NSArrayor 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];