如何在iPad Apps中解析JSON字符串?

时间:2012-01-13 08:50:29

标签: iphone objective-c ios

我想转换我的数据库中的图像以在我的iAd应用程序中检索它,为了这样做,我正在使用JSON,但我没有正确完成它。

在我的按钮onTouch里面,我写了这段代码

//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);

2 个答案:

答案 0 :(得分:2)

有不同的方法:

  1. 如果部署目标是iOS 5.0及更高版本,您可以使用:NSJSonSerialization
  2. 如果你想支持5.0以下的版本,可以使用众多库中的一个来做到这一点,我个人认为SBJson非常好。看看这个片段以获得一个想法:

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

答案 1 :(得分:1)

如果您的目标是iOS 5或更高版本,则可以使用NSJSONSerialization类。

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

如果你需要定位早期版本的iOS,你需要SBJSON或TouchJSON或类似的,但原则是相同的。

请同时阅读URL loading guide,您当前的代码会同步加载来自服务器的数据。如果这是主线程,UI将冻结,直到您获得数据或连接超时。