简体   繁体   English

如何处理从HTTP GET请求返回的JSON-Swift?

[英]How to handle JSON returned from HTTP GET request - Swift?

This is my code : 这是我的代码:

        let myUrl = NSURL(string:"hostname/file.php");

    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "GET";


    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        dispatch_async(dispatch_get_main_queue())
            {



                if(error != nil)
                {
                    //Display an alert message

                    return
                }



                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                    if let parseJSON = json { /* when the app reach here , will enter the catch and get out */

                        let userId = parseJSON["id"] as? String
                        print(userId)

                        if(userId != nil) 
                        {

                            NSUserDefaults.standardUserDefaults().setObject(parseJSON["id"], forKey: "id")
                            NSUserDefaults.standardUserDefaults().setObject(parseJSON["name"], forKey: "name")

                            NSUserDefaults.standardUserDefaults().synchronize()


                        } else {
                            // display an alert message
                                print("error")

                        }

                    }
                } catch
                {
                    print(error)
                }


        }



    }).resume()

my app getting the JSON from php file that parse the array from database into JSON and return it using echo and it return the following 2 rows : 我的应用程序从php文件获取JSON,该php文件将数据库中的数组解析为JSON并使用echo返回它,并返回以下两行:

[{"id":"1","name":"CIT","adminstrator_id":"1"},{"id":"2","name":"HelpDesk","adminstrator_id":"1"}]

When I print description of json I get nil 当我打印json描述时我得到nil

I tried to cast the json to NSArray , when I print first json[0] I get the first row which is good but when I tried to cast result of json[0] to NSDictionary still I'll get nil from it 我尝试将jsonNSArray ,当我打印第一个json[0]得到第一行,但是当我尝试将json[0]为NSDictionary时,我仍然会从中得到nil

when the app reach the if statement if let parseJSON = json it will enter the catch and it's not printing any error , I don't know why ? 当应用程序到达if语句时( if let parseJSON = json进入),它将进入捕获状态,并且未打印任何错误,我不知道为什么?

this my php code : 这是我的PHP代码:

    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "SELECT * FROM department";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($r = $result->fetch_assoc()) {
        $rows[] = $r;
    }
    $conn->close();
    echo json_encode($rows);
} else {
    $conn->close();
    echo "0 results";
}
?>

So is the problem in my request or with handling the request ? 那是我的请求还是处理请求中的问题?

The JSON is an array of [String:String] dictionaries. JSON是[String:String]字典的数组。

In a JSON string [] represents an array and {} represents a dictionary. 在JSON字符串中, []表示数组,而{}表示字典。

An URLRequest is not needed because GET is the default mode. 不需要URLRequest,因为GET是默认模式。 .MutableContainers is not needed either because the values are only read. 也不需要.MutableContainers ,因为仅读取值。

Consider that the JSON returns multiple records. 考虑到JSON返回多个记录。 This code just prints all values for id and name . 此代码仅显示idname所有值。

let myUrl = NSURL(string:"hostname/file.php")!
NSURLSession.sharedSession().dataTaskWithURL(myUrl) { (data, response, error) in
  if error != nil {
    print(error!)
  } else {
    do {
      if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:String]] {
        for entry in json {
          if let userId = entry["id"], name = entry["name"] {
            print(userId, name)
          }
        }
      } else {
        print("JSON is not an array of dictionaries")
      }
    } catch let error as NSError {
      print(error)
    }
  }
}.resume()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM