iPhone JSON Object

Posted by Cosizzle on Stack Overflow See other posts from Stack Overflow or by Cosizzle
Published on 2010-04-22T19:41:28Z Indexed on 2010/04/22 19:43 UTC
Read the original article Hit count: 462

Filed under:
|
|

Hello,

I'm trying to create a application that will retrieve JSON data from an HTTP request, send it to a the application main controller as a JSON object then from there do further processing with it.

Where I'm stick is actually creating a class that will serve as a JSON class in which will take a URL, grab the data, and return that object.

Alone, im able to make this class work, however I can not get the class to store the object for my main controller to retrieve it.

Because im fairly new to Objective-C itself, my thoughts are that im messing up within my init call:

-initWithURL:(NSString *) value
{
    responseData = [[NSMutableData data] retain];
    NSString *theURL = value;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    return self;
}

The processing of the JSON object takes place here:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSError *jsonError;
    SBJSON *json = [[SBJSON new] autorelease];
    NSDictionary *parsedJSON = [json objectWithString:responseString error:&jsonError];

    // NSArray object.
    listings = [parsedJSON objectForKey:@"posts"];
    NSEnumerator *enumerator = [listings objectEnumerator];
    NSDictionary* item;

    // to prove that it does work.
    while (item = (NSDictionary*)[enumerator nextObject]) {
        NSLog(@"posts:id = %@", [item objectForKey:@"id"]);
        NSLog(@"posts:address = %@", [item objectForKey:@"address"]);
        NSLog(@"posts:lat = %@", [item objectForKey:@"lat"]);
        NSLog(@"posts:lng = %@", [item objectForKey:@"lng"]);
    }

    [responseString release];

}

Now when calling the object within the main controller I have this bit of code in the viewDidLoad method call:

- (void)viewDidLoad {
    [super viewDidLoad];

    JSON_model *jsonObj = [[JSON_model alloc] initWithURL:@"http://localhost/json/faith_json.php?user=1&format=json"];

    NSEnumerator *enumerator = [[jsonObj listings] objectEnumerator];
    NSDictionary* item;
    //  
    while (item = (NSDictionary*)[enumerator nextObject]) {
        NSLog(@"posts:id = %@", [item objectForKey:@"id"]);
        NSLog(@"posts:address = %@", [item objectForKey:@"address"]);
        NSLog(@"posts:lat = %@", [item objectForKey:@"lat"]);
        NSLog(@"posts:lng = %@", [item objectForKey:@"lng"]);
    }
}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c