我有一个json字符串,我收到了一些API,如下所示:
[{"id": 2, "title": "Hello world!", "source": "htp://abc.com/hello_world", "blog": "abc.com", "rating": 0, "date": "2014-08-16T15:44:29Z", "tags": ["programming"]}, {"id": 1, "title": "Why we do not fly to space?", "source": "htp://habrahabr.ru/post/233119/", "blog": "habrahabr.ru", "rating": 5, "date": "2014-08-13T15:56:34Z", "tags": ["space", "science", "future"]}]
我这样收到:
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSArray *jsonArray = (NSArray*)JSONDictionary;
for (int i=0; i<=jsonArray.count-1; i++) {
NSDictionary *item = [jsonArray objectAtIndex:i];
. . .
NSString* tags = [item objectForKey:@"tags"];
. . .
}
所以现在我有了这个NSArray。除了标签,我可以提取所有内容 我试过了:
NSLog(@"Tags: %@", tags);
NSArray *json = [NSJSONSerialization
JSONObjectWithData:[tags dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
这给了我例外:
-[__NSCFArray dataUsingEncoding:]: unrecognized selector sent to instance 0x109399810
2014-08-17 14:45:48.224 ReadLater[38625:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray dataUsingEncoding:]: unrecognized selector sent to instance
然后,我试过这个:
NSArray *strings = [tags componentsSeparatedByString:@","];
这给了我例外:
-[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x1096a6680
2014-08-17 14:50:57.676 ReadLater[38758:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x1096a6680'
当我打印出标签变量时,它看起来像这样:
Tags: (
space,
science,
future
)
这是我可以告诉你的关于这个问题的一切。希望这能让你知道什么是错的,因为我怀疑我根本不了解这个特例。
非常感谢。
答案 0 :(得分:2)
Tags
不是字符串,而是数组。因此,要正确获取标记,请使用此
NSArray *tags = [item objectForKey:@"tags"];
要从JSON中的第一个字典中获取标记,您可以执行此操作
NSString *firstTag = tags[0]; //this would be "programming"