2017-06-28 60 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我的榮幸。快樂編碼:) –