2016-12-07 33 views
0

得到JSON我得到newDetails的值作为string.When我试试下面的代码我得到一个例外,因为无法从字符串

[__NSArrayI dataUsingEncoding:]:无法识别的选择发送到实例。

我宣布newDetail作为NSString。而且,在这个和下面的代码中的newDetail的值都是相同的。 下面的代码:

newDetail = [response valueForKey:@"newDetail"]; 
//newDetail prints as {"number":1,"nid":"1","pId":"3","name":"","me":"","day":"1"} 
     NSError *error; 
     NSData* data = [newDetail dataUsingEncoding:NSUTF8StringEncoding]; 
     NSDictionary* json = [NSJSONSerialization 
           JSONObjectWithData:data 
           options:kNilOptions 
           error:&error]; 

但是当我尝试下面的代码,它完美地运行:

newDetail = @" {\"number\":1,\"nid\":\"1\",\"pId\":\"3\",\"name\":\"\",\"me\":\"\",\"day\":\"1\"}";  
     NSError *error; 
     NSData* data = [newDetail dataUsingEncoding:NSUTF8StringEncoding]; 
     NSDictionary* json = [NSJSONSerialization 
           JSONObjectWithData:data 
           options:kNilOptions 
           error:&error]; 

谁能告诉我为什么我收到异常?

+0

我的猜测是,对于关键的“newDetail”值不一个字符串,但其他一些数据类型。可能[NSNull null]。 – Chris

+0

我正在打印newDetail的值,它不为空 – apurv

+0

而且您确定它是作为字符串而不是字典返回的?正在打印的行不明确。 – Chris

回答

1

在我看来,下面的代码返回一个NSArray

newDetail = [response valueForKey:@"newDetail"]; 

我怀疑,因为该错误信息,其中指出,试图调用该方法-dataUsingEncoding:一个NSArray对象上的这一点。

但是......你提到它打印,如:

{"number":1,"nid":"1","pId":"3","name":"","me":"","day":"1"} 

这将意味着这是一个的NSDictionary(键/值对)。

你可以登录类,以确保类似如下:

NSLog(@"%@", [newDetail class]); 

你的版本的作品,因为你硬编码字符串。你应该得到同样的错误,如果你想尝试序列化的NSDictionary或者甚至一个NSArray的成JSON字符串,像这样:

// This should result in the same error, since we serialize 
// an empty dictionary into a JSON string. 
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:@{} 
                options:kNilOptions 
                 error:&error]; 
+0

谢谢...能够解决它。 – apurv