小编典典

如何将JSON字符串反序列化为NSDictionary?(适用于iOS 5+)

json

在我的iOS 5应用中,我有一个NSString包含JSON字符串的。我想将该JSON字符串表示形式反序列化为本地NSDictionary对象。

 "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

我尝试了以下方法:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}"
                                options:NSJSONReadingMutableContainers
                                  error:&e];

但这会引发运行时错误。我究竟做错了什么?

-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'

阅读 256

收藏
2020-07-27

共1个答案

小编典典

看起来您在传递NSString参数,而应该在其中传递NSData参数:

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];
2020-07-27