JSON解析导致无法识别的选择器被发送

时间:2013-08-03 07:51:57

标签: objective-c json nsjsonserialization

我试图用我的JSON解析器解析以下内容。我尝试了几种方法,但实际的JSON序列化NSJSONSerialization总是抛出错误(实际上它是在NSArray * termArray = [dataDictionary objectForKey:@“term”]上引发的;但原因是,因为dataDictionary没有正确的响应所以我徘徊为什么,因为URL请求似乎有效。

  

'NSInvalidArgumentException',原因:' - [__ NSCFArray objectForKey:]:无法识别的选择器发送到实例

[
{
    "id": 20765985,
    "url": "http://quizlet.com/20765985/basic-portuguese-flash-cards/",
    "title": "Basic Portuguese",
    "created_by": "aUser",
    "term_count": 4,
    "created_date": 1362858462,
    "modified_date": 1362858462,
    "has_images": false,
    "subjects": [
        "Portuguese"
    ],
    "visibility": "only_me",
    "editable": "only_me",
    "has_access": true,
    "description": "",
    "has_discussion": true,
    "lang_terms": "pt",
    "lang_definitions": "en",
    "creator": {
        "username": "aUser",
        "account_type": "free",
        "profile_image": "https://quizlet.com/a/i/animals/38.ndeQ.jpg",
        "id": 6602337
    },
    "terms": [
        {
            "id": 696519541,
            "term": "mesa",
            "definition": "table",
            "image": null
        },
        {
            "id": 696519542,
            "term": "amigo",
            "definition": "friend",
            "image": null
        },
        {
            "id": 696519543,
            "term": "leite",
            "definition": "milk",
            "image": null
        },
        {
            "id": 696519544,
            "term": "vender",
            "definition": "sale",
            "image": null
        }
    ],
    "display_timestamp": "In March 2013"
}

这是我用来解析的代码

NSURL *myURL = [NSURL URLWithString:@"https://api.quizlet.com/2.0/users/<myUser>/sets?access_token=<myAccessToken>&whitespace=1"];

NSData *jsonData = [NSData dataWithContentsOfURL:myURL];

NSError *error = nil;

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSArray *termArray = [dataDictionary objectForKey:@"term"];

1 个答案:

答案 0 :(得分:0)

在您的JSON开头,您有一个[,这意味着JSON是一个数组。因此您无法将其作为字典访问。这就是为什么日志说它是一个数组而你得到了例外。