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

Posted

技术标签:

【中文标题】如何解析 JSON 数据对象内的数组内的数组?【英文标题】:How to parse an array inside array inside object of JSON data? 【发布时间】:2015-07-10 08:03:59 【问题描述】:

这是包含多个对象的 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);

【问题讨论】:

看来您正朝着正确的方向前进。有什么问题? NSDictionary* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; --OR-- NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; 它应该是NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"];,因为有一个数组针对键“continueWatching”。 我正在尝试:NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; for(NSArray *tmpArr1 in continueWatching) [title addObject:[tmpArr1 valueForKey:@"cursorPosition"]]; NSLog(@"oiajsdohioqsd5 %@",[tmpArr1 valueForKey:@"cursorPosition"]); @SamraanKhaan 这就是我在数组中获取 cursorPositions 的方式,现在正在处理 videoNames 【参考方案1】:

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

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);

【讨论】:

【参考方案2】:

此解决方案使用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);

【讨论】:

【参考方案3】:

你的代码会是这样的。

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.

【讨论】:

【参考方案4】:

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

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

您现在拥有一组视频属性。

NSSortDescriptor *sortDesc = [NSSortDecriptor sortDescriptorWithKey:@"id" ascending:YES];
NSArray *sortedVideosById = [continue sortedArrayUsingDescriptors:@[sortDesc]];

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

NSMutableArray *videoNames = [NSMutableArray array];
NSMutableArray *cursorPositions = [NSMutableArray array];

for( NSDictionary *v in sortedVideosById )

    NSArray *videoArray = (NSArray *)(v[@"video"]);
    NSDictionary *firstVideo = videoArray[0];
    videoNames addObject:firstVideo[@"videoName"];
    [cursorPositions addObject:v[@"cursorPosition"];

【讨论】:

以上是关于如何解析 JSON 数据对象内的数组内的数组?的主要内容,如果未能解决你的问题,请参考以下文章

iPhone JSON框架不解析不在对象或数组内的JSON字符串对象

如何使用json方法解析android中没有键名的数组内的嵌套json编码数组?

如何解析字典中的数组内的字典

Swift:如何在 TableView 内的 CollectionView 中显示解析的 JSON 数据?

如何使用php解析json数组并显示?

php解析json数组