2017-06-28 65 views
2

我在这里有以下代码,这是一个post请求与phpMyAdmin交谈的结果。以下JSON文件正在被服务器回显。如何从post请求中快速解析JSON 3

{"account:[{"login":"Nik","id":"0","consent":"0","surveyScore":"0","memoryScore":"0","towerScore":"0","tappingScore":"0"}]} 

现在我可以正确地将JSON放到我的手机上,但我无法解析它。

我一直在关注这里列出Xcode Json Example

莅临指导是我到目前为止的代码:

public func sqlAccount(login: String, pass: String, model:userModel) { 

// POST REQUEST Only, see php file for web service. 
let loci = "http://IPAddressConcealed/" 
let appended = loci + "account.php" 

var request = URLRequest(url: URL(string: appended)!) 
request.httpMethod = "POST" 
let postString = "login=\(login)&pass=\(pass)" 
request.httpBody = postString.data(using: .utf8)! 

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    if let reponse = response { 
     print(reponse) 
    } 
    if let data = data { 
     //print(data) 

     do{ 
      var accountJson: NSDictionary! 
      let json = try JSONSerialization.jsonObject(with: data, options: []) 
      accountJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary 
      print(json) 

      //getting the json array account from the response 

      let account: NSArray = accountJson["account"] as! NSArray; 

      // these two lines I am getting errors on 
      let login: String = account[0]["login"] as! String 
      let memoryScore: Int = account[0]["memoryScore"] as! Int 

     } catch { 
      print(error) 
     } 
    } 
} 
task.resume() 
}` 

这是在Xcode终端输出的结果,我只打印JSON数据之后。

 `{account =  (
      { 
     consent = 0; 
     id = 0; 
     login = Nik; 
     memoryScore = 0; 
     surveyScore = 0; 
     tappingScore = 0; 
     towerScore = 0; 
    } 
    ); }` 

后端PHP代码:

<?php 

// Create connection 
$con=mysqli_connect("localhost","root","root","sunnytest"); 

// Check connection 
if (mysqli_connect_errno()) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// This SQL statement selects ALL from the table 'Locations' 
//$sql = "SELECT * FROM accounts"; 



// Check if there are results 
if ($result = mysqli_query($con, $sql)) 
{ 
           // If so, then create a results array and a temporary one 
            // to hold the data 
            $response = array(); 

            $response['account'] = array(); 
            $tempArray = array(); 

            // Loop through each row in the result set 
            while($row = $result->fetch_object()) 
            { 
             // Add each row into our results array 
            $tempArray = $row; 
             array_push($response['account'], $tempArray); 
            } 

            // Finally, encode the array to JSON and output the results 
            printf(json_encode($response)); 
} 

// Close connections 
mysqli_close($con); 

?> 
+0

如果您的后端需要JSON,您为什么要将数据编码为.utf8?将其编码为JSON。在解码JSON时,不要使用NSDictionary和NSArray,而要使用本机Swift结构。 –

+0

我的后端不期望JSON,它是一个php文件,用于处理有关测试分数的帐户信息的发布请求。我刚刚按照上面列出的指南。 –

回答

1

尝试更换与此您的错误线。在你的代码中,你应该删除force unwrap并检查if let的值。我的回答只是解决您的错误的快速帮助。

let firstDic = account[0] as! NSDictionary 
let login = firstDic["login"] as! String 
let memoryScore = firstDic["memoryScore"] as! String 

print(login + " --- " + memoryScore) 
+0

这工作,谢谢方明 –

+0

@NikP我的荣幸。快乐编码:) –