Muaz Ishfaq
Muaz Ishfaq

Reputation: 276

Parse Nested objects and Array json in ios

I am trying to parse such json in which use many arrays and object How to parse it.

[
    {
        "MusicData": [
            {
                "user_music_id": "199",
                "music_id": "2",
                "music_name": "Country"
            },
            {
                "user_music_id": "200",
                "music_id": "2",
                "music_name": "Country"
            }
        ]
    },
    {
        "SportData": [
            {
                "user_sport_id": "179",
                "sport_id": "4",
                "sport_name": "Hockey"
            }
        ]
    },
    {
        "HobbyData": []
    },
    {
        "RelationData": []
    },
    {
        "MovieData": [
            {
                "user_movie_id": "144",
                "movie_id": "6",
                "movie_name": "Drama"
            }
        ]
    },
    {
        "BookData": []
    },
    {
        "CarrerData": [
            {
                "user_carrer_id": "186",
                "carrer_id": "7",
                "carrer_name": "Marketing"
            },
            {
                "user_carrer_id": "187",
                "carrer_id": "8",
                "carrer_name": "Sales"
            }
        ]
    }
]

MyMusic is a Dictionary and It has Array that has many Index.

How to parse its data one by one? using the label MyMusic, SportData etc.

I am trying to parse CarrerData from this json using this the following code:

musicTemp._id = [NSString stringWithFormat:@"%@",[[[responseDict objectAtIndex:0] valueForKey:@"MusicData"] valueForKey:@"user_music_id"]];

Upvotes: 1

Views: 2300

Answers (1)

Mat
Mat

Reputation: 7633

It seems that you're skipping an array, try with:

musicTemp._id = [NSString stringWithFormat:@"%@",[[[[responseDict objectAtIndex:0] valueForKey:@"MusicData"] objectAtIndex:0] valueForKey:@"user_music_id"]];`

The "{}" represents a Dictionary
The "[]" represents an Array

So to iterate over the objects you could do:

 NSArray* array=[[responseDict objectAtIndex:0] valueForKey:@"MusicData"]; 
   for (NSDictionary *dict in array) {
        NSString *userMusicID=[dict objectForKey:@"user_music_id"];
        NSString *musicID=[dict objectForKey:@"music_id"];
        //etc 
    }

You can do the same with the others elements.

Upvotes: 1

Related Questions