【问题标题】:I need to parse this JSON response make with http request in swift我需要用 swift 的 http 请求解析这个 JSON 响应
【发布时间】:2018-04-03 10:13:27
【问题描述】:

这是我在 php 中的脚本,有一个 Json 响应

<?php
include "dbconnect.php";

$id = $_POST['id'];
$uname = $_POST['uname'];

try {
 $queryExistingBike = "SELECT StatoBici, Username FROM BICI INNER JOIN UTENTE ON utenteKEY = KEYutente WHERE (IdBike = '$id')";
 $search = $connection->query($queryExistingBike);

    //print_r ($search);
} catch (Exception $ex) {
    echo $ex->getMessage();
}

$dati = $search->fetch_assoc();

if ($dati["Username"] == "$uname") {
  $dati['Username'] = "true";
} else {
  $dati['Username'] = "false";
}
//print_r($dati);
print json_encode($dati);
 ?>

这是来自 php 脚本的 Json 响应

{"StatoBici":"ok","Username":"false"}

这是快速向 Web 服务发出 http post 请求的代码

    func jsonResponse(){
        var request = URLRequest(url: URL(string: "http://bike1010.com/webservice/getBikeData.php")!)

        request.httpMethod = "POST"
        let postString = "id=2017&uname=admin"  // Your parameter
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")

            }

            let responseString = try? JSONSerialization.jsonObject(with: data, options:[])
            print(responseString)


        }

        task.resume()
    }

Xcode 的输出

Optional({
    StatoBici : Ok
    Username : Tue
})

【问题讨论】:

  • 那么问题是什么?您已经解析了 JSON 并打印了结果。你想达到什么目标?您想将其解析为一个对象,以使用每个结果值作为键?

标签: json swift post http-post


【解决方案1】:

如果这是你想要达到的:

let responseString = try? JSONSerialization.jsonObject(with: data, options:[]) as? [String:Any]
print(responseString)
//simple example for receiving each field from response
let statoBici:String = responseString["StatoBici"] as! String
let username:Bool = responseString["Username"] as! Bool
print("StatoBici received: \(statoBici), username received: \(username)")

【讨论】:

    【解决方案2】:

    正如 Wojcik 在评论中提到的,您已经解析了 JSON。您的 responseString 实际上是已解析的对象。您可以通过以下方式访问值:

    if let obj = responseString as? NSDictionary {
       let StatoBici = obj.value(for : "StatoBici") as! String
       let okValue   = obj.value(for : "OK") as! String // If OK is bool use bool
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多