【问题标题】:How to parse in JSON from post request swift 3如何从post request swift 3中解析JSON
【发布时间】:2017-12-01 22:37:12
【问题描述】:

我这里有以下代码,它是与 phpMyAdmin 交谈的发布请求的结果。服务器正在回显以下 JSON 文件。

{"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()
}`

这是我刚刚打印 JSON 数据后在 xcode 终端中的输出结果。

        `{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);

?>

【问题讨论】:

  • 如果你的后端需要 JSON,你为什么要在 .utf8 中编码你的数据?将其编码为 JSON。并且在解码 JSON 时,不要使用 NSDictionary 和 NSArray,而是使用原生 Swift 结构体。
  • 我的后端不需要 JSON,它是一个 php 文件,用于处理有关考试成绩的帐户信息的发布请求。我刚刚按照上面列出的指南进行操作。

标签: php ios json swift xcode


【解决方案1】:

尝试用这个替换你的错误行。在您的代码中,您应该删除强制展开并检查 if let 的值。我的回答只是解决您的错误的快速帮助。

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

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

【讨论】:

  • @NikP 很高兴。快乐编码:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多