Karna
Karna

Reputation: 1

How to parse JSON string in iPad Apps?

I want to convert the image in my database to retrieve it in my iAd apps and in order to do so i am using JSON ,but I am not getting it done properly.

Inside my button onTouch i have written this code

//create string contain url address for php file, the file name is phpFile.php,it receives parameter :name 
NSString *strURL=[NSString stringWithFormat:@"....my.php","hhhhh"];

//to execute php code
NSData *dataURL=[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; 

//to receive the returned Result 
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]self]; 
NSLog(@"%@",strResult);

Upvotes: 0

Views: 848

Answers (2)

yeforriak
yeforriak

Reputation: 1715

There are different ways of doing this:

  1. If you deployment target is iOS 5.0 and up you could use: NSJSonSerialization
  2. if you want to support versions below 5.0 you could use one of many libraries to do that, personally I find SBJson quite good. Take a look at this snippet to get an idea :

    NSString *dataString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [dataString JSONValue];
    NSArray * element = [dic objectForKey:@"jsonKey"];
    NSString * someSimpleElement = [dic objectForKey:@"jsonKey"];
    

Upvotes: 2

JeremyP
JeremyP

Reputation: 86651

If you are targeting iOS 5 or later, you can use the NSJSONSerialization class.

NSError& anError = nil;
id foo = [NSJSONSerialization JSONObjectWithData: dataURL options: 0 error: &anError];
if (foo == nil)
{
    // handle the error
}
else
{
    //play with the returned object
}

If you need to target an earlier version of iOS, you'll need SBJSON or TouchJSON or similar, but the princiiple is the same.

NB please also read the URL loading guide, your current code loads the data from the server synchronously. If this is the main thread, the UI will freeze until you have got the data or the connection times out.

Upvotes: 1

Related Questions