如何从字典的JSON数组中获取NSString?

时间:2014-06-10 13:01:52

标签: ios objective-c json

这是我的JSON:

-elements: [
    {
    HomeworkElementSession: {
        id: "608743",
        name: "Interval for x",
        description: "",
         }
    }
]
...

我能够达到一个实际的NSArray代表“elements”节点,因此在数组中只包含一个对象。 但我不知道如何达到这个字符串“name”。

我做的是:

NSMutableArray *elements = [singleHomework objectForKey:@"elements"];
            for(int i=0; i<elements.count; i++){
                NSDictionary* homeworkSession = [elements objectAtIndex:i];
                NSString* name = [homeworkSession objectForKey:@"name"];
                NSLog(@"%@",name);
            }

但我在Log中没有。

我做错了什么?

5 个答案:

答案 0 :(得分:1)

NSMutableArray *elements = [singleHomework objectForKey:@"elements"];
for(int i=0; i<elements.count; i++){
       NSDictionary* homeworkSession = [elements objectAtIndex:i];
       NSDictionary* dataDict = [homeworkSession objectForKey:@"HomeworkElementSession"];
       NSString* name = [dataDict objectForKey:@"name"];
       NSLog(@"%@",name);
 }

答案 1 :(得分:1)

您需要先获取关键字HomeworkElementSession的字典

NSMutableArray *elements = [singleHomework objectForKey:@"elements"];
            for(int i=0; i<elements.count; i++){
                NSDictionary* mainhomeworkSession = [elements objectAtIndex:i];
                NSDictionary* homeworkSession = [mainhomeworkSession objectForKey:@"HomeworkElementSession"];
                NSString* name = [homeworkSession objectForKey:@"name"];
                NSLog(@"%@",name);
            }

希望它可以帮助你......!

答案 2 :(得分:1)

NSMutableArray *elements = [singleHomework objectForKey:@"elements"];
for(NSDictionary *dict in elements){

       NSDictionary* dataDict = [dict objectForKey:@"HomeworkElementSession"];
       NSString* name = [dataDict objectForKey:@"name"];
       NSLog(@"%@",name);
 }

答案 3 :(得分:1)

试试这可能会有所帮助, 注意:您将获得NSString的输出,因此请使用此

 NSString *singleHomework = @"your data";
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[singleHomework dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:Nil];
NSMutableArray *dataArray = [dataDic valueForKey:@"elements"];
NSLog(@"Name Print %@",[dataArray[0] valueForKey:@"name"]);

答案 4 :(得分:0)

首先,我不确定为什么你在词典键中有一个连字符&#34; -elements&#34;。这可能是个问题。但是,您的主要问题是您的JSON是一个包含单个字典的数组,然后该字典包含具有属性的字典(HomeworkElementSession)。

NSString * json = @"{\"elements\": [{\"HomeworkElementSession\": {\"id\": \"608743\", \"name\":\"Interval for x\", \"description\": \"\"}}]}";
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];

NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&e];
NSLog(@"dict=%@", dict);