-1

here is the JSON data that has multiple object i just want to parse "continueWatching" object so i just shared it:

{
            "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"
                            }]
}

My code right now, i printed the whole JSON data and the message object, i need to get all "videoName" in a single array arranged by their "id" numbers plus i also want to get all "cursorPosition" in a single array arranged by their "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);
Nasir Khan
  • 723
  • 4
  • 12
  • 24
  • It looks like you are going in the right direction. What's the issue? – trojanfoe Jul 10 '15 at 08:08
  • NSDictionary* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; --OR-- NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; – Samraan Khaan Jul 10 '15 at 08:25
  • it would be `NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"];` because there is an array against the key "continueWatching". – Mahesh Agrawal Jul 10 '15 at 08:29
  • I am trying: NSArray* continueWatching = [[dict objectForKey:@"message"] objectForKey:@"continueWatching"]; for(NSArray *tmpArr1 in continueWatching){ [title addObject:[tmpArr1 valueForKey:@"cursorPosition"]]; NSLog(@"oiajsdohioqsd5 %@",[tmpArr1 valueForKey:@"cursorPosition"]);} – Nasir Khan Jul 10 '15 at 08:33
  • @SamraanKhaan so that's how i am getting cursorPositions in an array, now working on videoNames – Nasir Khan Jul 10 '15 at 08:38
  • possible duplicate of [How do I parse JSON with Objective-C?](http://stackoverflow.com/questions/5547311/how-do-i-parse-json-with-objective-c) – AJPatel Jul 10 '15 at 08:43

4 Answers4

1

I do not get any very elegant way of doing this but this will solve your problem

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);
iHulk
  • 4,869
  • 2
  • 30
  • 39
0

this solution uses valueForKeyPath to extract the requested objects without loops. The array continueWatchingArray is sorted before getting the properties. Therefore the resulting arrays videoNameArray and cursorPositionArray are sorted, too

  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);
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Your code will be like this.

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.
Mahesh Agrawal
  • 3,348
  • 20
  • 34
0

JSON object "message" is a dictionary and not an array.

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

You now have an array of your videos's properties.

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

You now have an array of your videos's properties, sorted by video's id. Parse it to collect video names and cursorPosition in arrays, sorted by 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"];
}
Nicolas Buquet
  • 3,880
  • 28
  • 28