简体   繁体   中英

How to parse nested JSON objects?

I get the JSON format like this:

stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})

What I want to get is an array for the "ios". This is my code:

id jsonObjects = [NSJSONSerialization JSONObjectWithData:
                  jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
    NSArray *ios_data = [[[dataDict objectForKey:@"posts"] objectForKey:@"CHANNEL"] objectForKey:@"ios"];
    NSLog(@"%@",ios_data);
    dict = [NSDictionary dictionaryWithObjectsAndKeys:ios_data, ios,nil];

}

but it return in NULL, what the problem of it?

Your "JSON":

stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})

Is not JSON. You can try running it through a validator like http://jsonlint.com/ to test it out.

Also, you should create an NSError reference to pass in instead of nil so NSJSONSerialization can vend you an error object. This will help in your debugging.


Here is an example of what your data would look like if it were valid JSON:

{
    "stream": [
        {
            "posts": [
                {
                    "CHANNEL": {
                        "ios": "(format=m3u8-aapl).m3u8"
                    }
                }
            ]
        }
    ]
}

(I spaced it out to be more legible, but the spacing is unnecessary for parsing.)

Once you have your array holding 'posts' you can drill down like this:

NSArray *fileData = [myDic1 valueForKeyPath:@"posts.CHANNEL"];

and then access like this:

for (int i=0; i < [clientFileData count]; i++) {
NSDictionary *myDictionary = [fileData objectAtIndex:i];
]

Also, unless I am wrong, your JSON file seems incorrectly formatted.

Get your response like:

NSDictionary *dictionaryData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

Correct JSOn should be like this

{
   "posts":[
      {
         "CHANNEL":{
            "ios":"(format=m3u8-aapl).m3u8"
         }
      }
   ]
}

Get the correct format of JSON and then try to parse it. And one thing you were doing wrong is POST is an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM