2017-07-06 149 views
0

我有一個應用程序,允許您輸入數據並將其發佈到運行我創建的mysql的服務器上。然後,我編寫了PHP文件將mysql轉換爲JSON,以便我的應用程序可以列出表中的內容。然而,它不工作,我收到錯誤說「字符0周圍的無效值」或「JSON文本沒有開始數組或對象」。我想要做的就是獲取數據並將其轉換爲索引,以便我可以在整個應用中顯示某些數據。使用Swift 3解析JSON 3 XCode 8

PHP代碼:

//including the file dboperation 
require_once '../includes/DbOperation2.php'; 

//creating a response array to store data 
$response = array(); 

//creating a key in the response array to insert values 
//this key will store an array iteself 
$response['profile'] = array(); 

//creating object of class DbOperation 
$db = new DbOperation(); 

//getting the teams using the function we created 
$profile = $db->getAllUsers(); 

//looping through all the teams. 
//creating a temporary array 
$temp = array(); 

//inserting the team in the temporary array 
$temp['id'] = $profiles['id']; 
$temp['displayName']=$profiles['displayName']; 
$temp['department']=$profiles['department']; 
$temp['mamager']=$profiles['mamager']; 
$temp['office']=$profiles['office']; 
$temp['util']=$profiles['util']; 

//inserting the temporary array inside response 
array_push($response['profile'],$temp); 
} 

//displaying the array in json format 
echo json_encode($response); 

輸出看起來是這樣的:

{"profile":[{"id":1,"displayName":"Jacob Blacksten","department":"DF","mamager":"San","office":"NYC","util":2},{"id":2,"displayName":"John Smith","department":"SS","mamager":"Jack","office":"Boston","util":3}]} 

的Xcode:

guard let url = URL(string: "http://ipAddress/MyWebService/api/getteams.php") else { return} 

    let session = URLSession.shared 
    session.dataTask(with: url) { (data, response, error) in 
     if let response = response { 
      print(response) 
     } 

     if let data = data { 
      print(data) 
      do { 
       let json = try JSONSerialization.jsonObject(with: data, options: []) 
       print(json) 
      } catch{ 
       print(error) 
      } 
     } 
    }.resume() 
} 

請有人幫我的Xcode。我需要先解析並解析,然後將它們放入數組中併爲它們編制索引。我知道這可能是一個重複的問題,但我花了幾天的時間尋找這個答案,我不知道編碼足以理解一切。

+0

嘗試標記更窄比這個。我根本沒有看到任何與MySQL相關的東西,而Xcode並不直接相關。如果問題出現在您的PHP代碼中,請確保在您的Swift代碼正常工作之前,該服務器端組件的輸出是正確的。 – tadman

+0

你說得對,MySQL標籤不正確。在上面你會看到服務器給我的輸出。這正是我讀過的所有文章都是如此。對我來說,我錯過了xcode中的一些東西,但我不知道是什麼。 –

+0

這個錯誤來自哪裏?當你調試你的Swift代碼時,你會在'data'中獲得正確的JSON字符串嗎? – tadman

回答

0

有很多方法可以解析這個。這是我的方式。

首先,創建一個NSObject您將要分析的鍵的類。

class DataObject: NSObject { var Name: String? var ID: String? 

} 

在你的ViewController類(或任何你有你的方法獲取數據),創建類型的全局變量數據對象

var dataObject = [DataObject]() 

func retrieveData(dataToParse: [String : Any]) { 

//dataToParse will be your json variable and cast it as a dictionary of [String : Any] 

let object = DataObject() 
object.setValuesForKey(dataToParse) 
dataObject.append(object) 

} 

現在您可以訪問,就像一個陣列數據,還挺。

let name = dataObject[0].Name