Pregunta

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.

¿Fue útil?

Solución

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)

Otros consejos

What have you tried?

NSArray *array = [dataURL objectFromJSONData];
NSAssert([array isKindOfClass:[NSArray class]], @"This should be an array.");

for (NSNumber *value in array) {
    NSAssert([value isKindOfClass:[NSNumber class]], @"This should be a number.");

    NSLog(@"%@", value);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top