如何使用NSJSONSerialization从多级JSON创建NSDictionary

时间:2012-11-04 04:48:27

标签: xcode json ios6 nsdictionary nsjsonserialization

JSON示例:

注意:“Docs”数组是此大型数组中众多不同数组之一 阵列。

 {
        "Docs": {
            "Title1": {
                "id": "1",
                "active": "0",
                "title": "xxx",
                "date": "October 22, 2012",
                "description": "Description here",
                "ext": "DOCX",
                "when": "Tuesday, October 23",
                "subject": "French",
                "author": "xx xD",
                "email": "xx.xx@gmail.com",
                "day": "Tuesday, October 23",
                "dl": "9 downloads"
            },
            "Title2": {
                "id": "2",
                "active": "0",
                "title": "Vocab, Page 64",
                "date": "October 22, 2012",
                "description": "Description goes here",
                "ext": "XLSX",
                "when": "Tuesday October23",
                "subject": "French",
                "author": "xxxxxx",
                "email": "xxx@yahoo.com",
                "day": "Tuesday October23",
                "dl": "3 downloads"
            }
        }

如何制作获得“Docs”数组(Docs)标题的NSDictionary,并获取docs数组中数组数量的计数?谢谢。我对如何做到这一点非常困惑。

1 个答案:

答案 0 :(得分:3)

这样的事情:

NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];

获得反序列化数据后,您可以遍历字典以读取元素。要获得对象数量的计数:

// Get your object "Docs" from the root object
NSDictionary *dictionaryObject = (NSDictionary *)[JSON objectForKey:@"Docs"];

// Get the count by counting the keys
NSArray * allKeys = [dictionaryObject allKeys];
NSLog(@"Count : %d", [allKeys count]);