【问题标题】:post request can't return an NSDictionary in swift发布请求无法快速返回 NSDictionary
【发布时间】:2015-07-18 08:31:30
【问题描述】:

我正在快速发出POST 请求,但我的代码无法将数据收集为NSDictionary。

let myUrl = NSURL(string: "http://www.mindyour.money/individual_players_by_sport_history.php");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    let postString = "token=\(token)&sport=\(sports)";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

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

        var err: NSError?

        var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: nil) as? NSDictionary

        var json : JSON = JSON(data: data)

但是,如果我转换为NSArray,这很容易被接受。我之前已经成功地收集为NSDictionary,但只能从NSData 对象中收集。有人可以帮我吗?

子文件的例子应该是这样的;

    [
  {
    "gametype" : "Football FantasyLeagueGame",
    "player_username" : "BarryManilow",
    "event" : "Rep. of Ireland v England - Coupon",
    "stake" : "5.00",
    "seat_created" : "2015-06-07 12:14:51",
    "game_end_time" : "2015-06-07 14:50:00",
    "numseats" : "1"
  }]

我使用其中几个键值来创建一个类数组,稍后在代码中,我以后可能会有更多问题。道歉。

【问题讨论】:

  • 也许让 postString = "?token=(token)&sport=(sports)";

标签: php ios json swift nsdictionary


【解决方案1】:

服务返回的 JSON 是一个游戏数组。在 JSON 中,[...] 中的内容表示一个项目数组。 NSDictionary 只能表示一个 JSON 对象,这就是您的 JSON 数组所包含的内容。因此,JSONObjectWithData 返回的id 应该转换为NSArray。

【讨论】:

  • 谢谢尼克拉斯,明白了!
  • 为了完整起见,我更改了 php 以生成如下 JSON; {“试用”:[{“游戏类型”:“足球 FantasyLeagueGame”,“player_username”:“BarryManilow”,“事件”:“爱尔兰对英格兰 - 优惠券”,“赌注”:“5.00”,“seat_created” : "2015-06-07 12:14:51", "game_end_time" : "2015-06-07 14:50:00", "numseats" : "1" }]} 然后通过 if let for [NSDictionary ]
猜你喜欢
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多