【问题标题】:JSON_encode outputs correctly in browser, yet print(json) in Swift outputs 'nil', why?JSON_encode 在浏览器中正确输出,但 Swift 中的 print(json) 输出'nil',为什么?
【发布时间】:2016-11-07 10:08:11
【问题描述】:

我的 JSON 在 XCode 中被输出为 NIL 时遇到问题,即使我在浏览器中进行测试时它会报告正确的值。

$player1Id = array();
$player1Id = getPlayer1Id($player1name,$communityId);

public function getPlayer1Id($playerName, $communityId)
{

$returnValue = array();

$sql = "SELECT users.id\n"
. "FROM users\n"
. "join community_players\n"
. "on community_players.player_id=users.id \n"
. "WHERE users.user_name = '".$playerName."' AND community_players.community_id = '".$communityId."'";

$result = $this->conn->query($sql);
    if($result != null && (mysqli_num_rows($result) >= 1 )){
        $row = $result -> fetch_array(MYSQLI_ASSOC);
        if(!empty($row)){
            $returnValue = $row['id'];
        }
    }
    return $returnValue;
}

echo json_encode(array($player1Id));

如果我在浏览器中使用 URL 中的一组值进行测试,它会正确输出:

[“31”]

这是我的 Swift 函数:

func submit(action: UIAlertAction){
//    print (homePlayerLabel.text!,":",homeTeamLabel.text!,homeGoals,"(",player1result!,") - ", awayPlayerLabel.text!,":",awayTeamLabel.text!,awayGoals,"(",player2result!,")")


    // Send user data to server side

    let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/submitScore.php");

    var request = URLRequest(url:myUrl!);
    request.httpMethod = "POST";

    let postString = "communityId=\(communityId!)&player1name=\(homePlayerLabel.text!)&player1team=\(homeTeamLabel.text!)&player1goals=\(homeGoals)&player1result=\(player1result!)&player2name=\(awayPlayerLabel.text!)&player2team=\(awayTeamLabel.text!)&player2goals=\(awayGoals)&player2result=\(player2result!)";

    print (postString)
    request.httpBody = postString.data(using: String.Encoding.utf8);


    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in


        DispatchQueue.main.async
            {


                if error != nil {
                    print("error=\(error)")
                    return
                }

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                    print (json)

                    if let parseJSON = json {

                        let returnValue = parseJSON["status"] as? String

                        if( returnValue == "Success")
                        {
                            let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);


                            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in

                                self.dismiss(animated: true, completion: nil)

                            }

                            myAlert.addAction(okAction);
                            self.present(myAlert, animated: true, completion: nil)

                        } else {


                            let errorMessage = parseJSON["message"] as? String
                            if(errorMessage != nil)
                            {

                                self.displayMyAlertMessage(userMessage: errorMessage!);

                            }

                        }

                    }
                } catch{
                    print(error)
                }



        }

    }

    task.resume()



}

然而,当我在 Xcode 中 print (json) 报告为:

无

有什么明显我看不下去的地方吗?

【问题讨论】:

  • 您的回复是Array of String 类型不是Dictionary,因此您需要将其转换为[String] 而不是[String:Any]
  • 我已将行更改为 - let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:String] 但仍然为零
  • 正确检查我写的评论[String]不是[String:String]。
  • 太棒了!这样就解决了。

标签: php ios json xcode


【解决方案1】:

我认为您将 php 更新到 7.1 我在将 php 更新到 7.1 时遇到了同样的问题 try to put mysql_query('SET CHARACTER SET utf8') 我认为它可以解决您的问题

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 2022-11-08
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多