2014-03-25 29 views
2

就像標題所說,我的UITextView設置爲打印在「userName」中找到的數據。而不是適當的行爲,它打印「用戶名」。UITextView打印JSON標識符而不是所需的解析數據

PHP代碼:

<?php 

    header('Content-Type: application/json'); 

    $arr = array ('userName'=>'derekshull', 'userBio'=>'This is derekshulls bio','userSubmitted'=>'15'); 
    echo json_encode($arr); 


?> 

目標C:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 


    NSURL *myURL = [[NSURL alloc]initWithString:@"http://techinworship.com/json.php"]; 
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL]; 
    NSError *error; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error]; 

    if(!error) 
    { 
     for (id element in jsonArray) { 
      textview.text = [NSString stringWithFormat:@"%@", [element description]]; 
      // text view will contain last element from the loop 
     } 
    } 
    else{ 
     textview.text = [NSString stringWithFormat:@"Error--%@",[error description]]; 
    } 
} 

缺少什麼我在這裏?另外,運行時,應用程序不會崩潰並出錯。但是,DeBug區域記錄了以下內容。

2014-03-24 20:20:53.258 testtest[11434:60b] Unknown class textview in Interface Builder file. 

回答

1

我目前沒有OSX電腦可用,所以我無法評估我的代碼。

它看起來像你在你身邊的數組PHP代碼是一個關聯數組和JSON類似。當你在你的Obj-C代碼中解析JSON字符串時,嘗試將它分配給NSDictionary,這樣你就可以訪問關聯數組。

NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error]; 

當使用在jsonArray數據不重複它,使用NSDictionary的方法objectForKey得到得到你想要的值。

舉個例子,得到的userName值,你可以這樣做:

[jsonArray objectForKey: @"userName"] // jsonArray is not actually a array, but a dictionary now 

而要改變TextView的文本,你可以做到以下幾點:

textview.text = [NSString stringWithFormat:@"%@", [jsonArray objectForKey: @"userName"]]; 

問如果有什麼不清楚的話!

乾杯!

+0

就是這樣!非常感謝!真的很感謝徹底的答案! – davidrayowens

+0

沒問題。很高興幫助朋友出去! :) –

+0

想知道如果我可能會麻煩你讓我知道這個傢伙的問題和我的區別。我覺得我們有完全相同的問題,但爲他工作的解決方案根本不適用於我......? [鏈接](http://stackoverflow.com/questions/19363182/how-to-get-a-value-from-a-json-object-using-nsjsonserialization) – davidrayowens