如何解析JSON数据对象内的数组内的数组?

时间:2015-07-10 08:03:59

标签: ios objective-c arrays json parsing

这里是具有多个对象的JSON数据我只想解析" continueWatching"对象,所以我只是分享它:

{
            "message": {
                "continueWatching": [{
                                "id": "2",
                                "video": [{
                                        "videoName": "fsfdsf",
                                        "coverPicture": ""
                                    }
                                ],
                                "cursorPosition": "12:32:25",
                                "dateWatched": "2015-07-08 00:00:00",
                                "updated": "2015-07-15 12:12:34"
                            }, {
                                "id": "1",
                                "video": [{
                                        "videoName": "Hello",
                                        "coverPicture": ""
                                    }
                                ],
                                "cursorPosition": "15:42:41",
                                "dateWatched": "2015-07-02 00:00:00",
                                "updated": "2015-07-02 00:00:00"
                            }, {
                                "id": "3",
                                "video": [{
                                        "videoName": "adfafadf",
                                        "coverPicture": ""
                                    }
                                ],
                                "cursorPosition": "12:32:25",
                                "dateWatched": "2015-07-01 00:00:00",
                                "updated": "2015-07-02 00:00:00"
                            }]
}

我的代码现在,我打印了整个JSON数据和消息对象,我需要得到所有" videoName"在由他们的" id"排列的单个阵列中数字加上我也想得到所有" cursorPosition"在由他们的" id"

排列的单个数组中
NSString *myRequestString = [NSString stringWithFormat:@"getRecommendations=all&profileId=1"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url];
// set Request Type
[request setHTTPMethod: @"POST"];
// Set content-type
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@",response);

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
BOOL boolean=[[dict  objectForKey:@"boolean"]boolValue];

NSArray *message=[dict objectForKey:@"message"];
NSLog(@"kajhsdahfohofhoaehfpihjfpejwfp%@",message);

4 个答案:

答案 0 :(得分:3)

我没有得到任何非常优雅的方法,但这将解决你的问题

NSArray *continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"];

//sort all objects using id.
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES selector:@selector(localizedStandardCompare:)];
continueWatching = [continueWatching sortedArrayUsingDescriptors:@[sortDesc]];
NSMutableArray *cursorPosition = [NSMutableArray array];
NSMutableArray *videoNames = [NSMutableArray array];

[continueWatching enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //find all videos array and then again enumerate it and extract all video names
    NSArray *videos = [obj objectForKey:@"video"];
    [videos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [videoNames addObject:[obj objectForKey:@"videoName"]];
    }];
    //extract all curser positions and save them
    [cursorPosition addObject:[obj objectForKey:@"cursorPosition"]];
}];



NSLog(@"%@",cursorPosition);
NSLog(@"%@",videoNames);

答案 1 :(得分:0)

此解决方案使用valueForKeyPath来提取所请求的对象而不使用循环。 在获取属性之前对数组continueWatchingArray进行排序。 因此,生成的数组videoNameArraycursorPositionArray也会被排序

  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
  NSArray *continueWatchingArray = [[dict valueForKeyPath:@"message.continueWatching"] sortedArrayUsingDescriptors:@[sortDescriptor]];
  NSArray *cursorPositionArray = [continueWatchingArray valueForKeyPath:@"cursorPosition"];
  NSArray *videoNameArray = [continueWatchingArray valueForKeyPath:@"video.videoName"];
  NSMutableArray *tempArray = [[NSMutableArray alloc] init];
  // repeat loop to flatten the array
  for (NSArray *subArray in videoNameArray) {
    [tempArray addObject:subArray[0]];
  }
  videoNameArray = tempArray;
  NSLog(@"%@", videoNameArray);
  NSLog(@"%@", cursorPositionArray);

答案 2 :(得分:0)

您的代码将是这样的。

NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"];
continueWatching = [continueWatching sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]]];

NSMutableArray *arrayOfVideos = [[NSMutableArray alloc]init];
NSMutableArray *arrayOfCursors = [[NSMutableArray alloc]init];

for(NSDictionary *dicData in continueWatching){
    NSArray *videoArray = [dicData objectForKey:@"video"];
    [arrayOfVideos addObjectsFromArray:videoArray];

    [arrayOfCursors addObject:[dicData valueForKey:@"cursorPosition"]];
}

//now in the two arrays you will have the required result.

答案 3 :(得分:0)

JSON对象"消息"是字典而不是数组。

use Data::Dumper; print Dumper scalar $cgi->Vars();

您现在拥有一系列视频的属性。

$VAR1 = bless( {
                 'use_tempfile' => 1,
                 '.fieldnames' => {},
                 '.charset' => 'ISO-8859-1',
                 '.parameters' => [
                                    'foo[foo1]',
                                    'foo[foo2]'
                                  ],
                 'escape' => 1,
                 'param' => {
                              'foo[foo2]' => [
                                               'bar2'
                                             ],
                              'foo[foo1]' => [
                                               'bar¹'
                                             ]
                            }
               }, 'CGI' );

您现在拥有一系列视频的属性,按视频的ID排序。 解析它以收集数组中的视频名称和cursorPosition,按ID分类。

NSDictionary *messages = [dict objectForKey:@"message"];
NSArray *continue = [messages objectForKey:@"continueWatching"];