[英]json is not parsing correctly in objective-c
I'm trying to parse my JSON into an NSDictionary. 我正在尝试将JSON解析为NSDictionary。 Here is the method that I use for parsing.
这是我用于解析的方法。
+ (NSDictionary *)executeGenkFetch:(NSString *)query
{
query = [NSString stringWithFormat:@"%@", query];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query);
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);
return results;
}
And here is how I use this function. 这就是我使用此功能的方法。
+(NSArray *)getCommentsWithParam:(NSString *)Param
{
NSString *request = [NSString stringWithFormat:@"https://graph.facebook.com/comments/?ids=%@",Param];
NSLog(@"request is %@",request);
NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param];
return [[self executeGenkFetch:request] valueForKey:vfk];
}
The problem is when I log the NSArray that I get back from getCommentsWithParam, I always get NULL. 问题是,当我记录从getCommentsWithParam返回的NSArray时,总是得到NULL。 But when I look at the log from
但是当我从
NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);
I get the JSON I want. 我得到了想要的JSON。 Any help on what is going wrong?
有什么问题的帮助吗?
It is difficult to say without seeing the actual JSON data, but probably in 看不到实际的JSON数据很难说,但是可能
NSString *vfk = [NSString stringWithFormat:@"%@.comments.data",Param];
return [[self executeGenkFetch:request] valueForKey:vfk];
you have to use valueForKeyPath
instead of valueForKey
, because vfk
is a key path with several key components (separated by the dots). 您必须使用
valueForKeyPath
而不是valueForKey
,因为vfk
是具有多个关键组成部分(由点分隔)的关键路径 。
Update: Another problem is that the top-level key Param
is a HTTP URL and contains dots. 更新:另一个问题是顶级密钥
Param
是HTTP URL,并且包含点。 But in key-value coding dots are used to separate the key components. 但是在键值编码中,点用于分隔键组成部分。 Therefore you cannot use
Param
as a key component. 因此,您不能将
Param
用作关键组件。 Use objectForKey
for the top-level key instead: 使用
objectForKey
作为顶层密钥:
NSDictionary *results = [self executeGenkFetch:request];
return [[results objectForKey:Param] valueForKeyPath:@"comments.data"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.