2012-01-13 45 views
0

我想轉換數據庫中的圖像以在我的iAd應用程序中檢索它,爲了做到這一點,我使用了JSON,但是我沒有正確地完成它。如何解析iPad應用中的JSON字符串?

在我的按鈕onTouch如果你的目標iOS 5中我寫了這個代碼

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

你能詳細您已經嘗試什麼,你的代碼? – aqua 2012-01-13 08:55:06

+0

我的按鈕onTouch裏面我寫了這段代碼 //創建字符串包含php文件的url地址,文件名是phpFile.php,它接收參數:name NSString * strURL = [NSString stringWithFormat:@「http:// WWW ..... my.php」, 「HHHHH」]; //執行php代碼 NSData * dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; //收到返回的結果 NSString * strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding] self]; NSLog(@「%@」,strResult); – Karna 2012-01-13 09:08:26

+0

我想分析這一點,並從上面的字符串獲取所有細節,然後顯示所有這些在我的應用程序 – Karna 2012-01-13 09:13:57

回答

1

或更高版本,可以使用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或相似,但princiiple是一樣的。

NB請同時閱讀URL loading guide,您當前的代碼同步從服務器加載數據。如果這是主線程,則UI將凍結,直到獲取數據或連接超時。

+0

在我的Json文件夾中顯示錯誤的所有.m文件版本不可用如何解決這些錯誤 – Karna 2012-01-13 10:49:04

+0

是的!我使用ios 5作爲我的目標設備可以有人詳細說明NSSerialization和各自的編碼? – Karna 2012-01-13 12:02:41

+0

我無法詳細說明'NSJSONSerialization',因爲這實際上幾乎就是它的全部。 – JeremyP 2012-01-13 15:29:50

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"]; 
    
+0

是的!我使用ios 5作爲我的目標設備可以有人詳細說明NSSerialization和各自的編碼? – Karna 2012-01-13 12:03:45