Search code examples
phpobjective-cjsonuitableviewjsonkit

very basic JSON to tableView (iOS)


Well, I decided that it's time to learn a new skill, programming objective-c. My programming knowledge is very minimal, It consists of PHP, little bit of HTML, and a little bit of MySQL. What I want to do is take some JSON that is made with php and populate a iOS table view.

here is my json.php:

<?php
$array = array(1,2,3,4,5,6,7,8,9,10);
$json = json_encode($array);
echo $json;
?>

My only problem is, is I have no idea where to start on how to use JSONKit framework. https://github.com/johnezang/JSONKit/ I would prefer to use JSONKit over the other alternatives just because it seems it has more support.

NSString *strURL = [NSString stringWithFormat:@"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(@"%@", strResult);

I was able to print the results of the JSON page in the debug console. Now my only question is what next? I have tried to look for some tutorials online but all I could find was something more advanced Jason phraser. To advanced for my basic needs. I know my questions very vague and open to a lot of different answer, but I figured this is the place to ask these types of questions.


Solution

  • iOS has its own JSON parse now called NSJSONSerialization.

    http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

    You can have a look. I always use it like this.

    [NSJSONSerialization JSONObjectWithData:tmpData
                                           options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments 
                                             error:nil]
    

    sample by modifying your code:

    NSString *strURL = [NSString stringWithFormat:@"http://api.tekop.net/json.php"];
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    NSArray *arrayResult = [NSJSONSerialization JSONObjectWithData:dataURL
                                           options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments 
                                             error:nil];
    
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    

    Something to note is that, if your json is an array based, use NSArray to store the result. If your json is an hash based, use NSDictionary. (Hope I say it clearly, I dont know the related terms to describe)