Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

iphone - JSON Parsing in Objective-C

I've done the Raywenderlich tutorial about JSON in iOS but I got difficulties to adapt it to my own JSON file. Here is my JSON:

{
    "Albumvideo":[
    {
        "titre": "Publicit??",
        "photo":"blabla.jpg"
    },
    {
        "titre": "Events",
        "photo":"blabla.jpg"
    }
    ]
}

Here is my Code:

- (void) viewDidLoad
{
    [super viewDidLoad];
    dispatch_async (kBgQueue, ^{
         NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
        [self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
    });
}

- (void)fetchedData:(NSData *)responseData {
     NSError* error;
     NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
     NSArray* albumsvideo = [json objectForKey:@"titre"];
     NSLog(@"Album: %@", albumsvideo);
}

Log returns null.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are doing it wrong. You have filled your JSON Data in your Dictionary (named json) correctly. But then you have an Array of Dictionaries (called Albumvideo) inside your Main Dictionary and value of titre is inside Albumvideo Array.

The Correct Code is :

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsvideo = [json objectForKey:@"Albumvideo"];
NSString *titre1 = [[albumsvideo objectAtIndex:0]valueForKey:@"titre"];
NSString *titre2 = [[albumsvideo objectAtIndex:1]valueForKey:@"titre"];

Understand the Concept. It depends on what you have inside your JSON. If it's an Array ( Values inside [ ]) then you have to save in NSArray, if it's a Dictionary ( Values inside { }) then save as NSDictionary and if you have single values like string , integer, double then you have to save them using appropriate Objective-C Data types.

Hope, you got some proper idea about JSON Parsing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...