使用Swift 3解析JSON 3 XCode 8

使用Swift 3解析JSON 3 XCode 8

问题描述:

我有一个应用程序,允许您输入数据并将其发布到运行我创建的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

有很多方法可以解析这个。这是我的方式。

首先,创建一个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