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

时间:2022-10-24 14:01:43

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,将数组从数据库解析为JSON并使用echo返回它,它返回以下2行:

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

When I print description of json I get nil

当我打印json的描述时,我得到零

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

我试图将json转换为NSArray,当我首先打印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语句时,如果让parseJSON = json,它将进入catch并且它不会打印任何错误,我不知道为什么?

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 ?

我的请求或处理请求的问题是什么?

1 个解决方案

#1


2  

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. .MutableContainers is not needed either because the values are only read.

不需要URLRequest,因为GET是默认模式。不需要.MutableContainers,因为只读取值。

Consider that the JSON returns multiple records. This code just prints all values for id and name.

考虑JSON返回多个记录。此代码只打印id和name的所有值。

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()

#1


2  

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. .MutableContainers is not needed either because the values are only read.

不需要URLRequest,因为GET是默认模式。不需要.MutableContainers,因为只读取值。

Consider that the JSON returns multiple records. This code just prints all values for id and name.

考虑JSON返回多个记录。此代码只打印id和name的所有值。

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()