无法使用SwiftyJSON访问JSON

时间:2016-02-06 17:27:11

标签: json swift dictionary swifty-json

我正在尝试访问通过Alamofire获取的JSON:

func getDataFromServer() {
    Alamofire.request(.POST, websiteURL, parameters: myParameters) .responseString {
        (response) -> Void in
        if let value = response.result.value {
            let json = JSON(value)
            self.parseJSON(json)
        }
    }
}

,并且返回给我的JSON看起来像这样:

{  
"status":"success",
"object":[  
  {  
     "name":"Bob",
     "age":"20 ",
  },
  {  
     "name": "Jane",
     "age":"25"
  },
]
}

我使用SwiftyJSON访问名称:

func parseJSON(json: JSON) {
    for result in json["object"].arrayValue {
        print(result["name"].stringValue)
    }
}

但它没有打印任何东西。我做错了吗?

4 个答案:

答案 0 :(得分:2)

应使用

responseJSON代替responseString

答案 1 :(得分:0)

您的JSON无效

{
  "status": "success",
  "object": [
    {
      "name": "Bob",
      "age": "20 ",

    },
    {
      "name": "Jane",
      "age": "25"
    }, <--Delete this comma

  ]
}

答案 2 :(得分:0)

管理以找出我的代码有什么问题。当我使用Alamofire发出POST请求时,我将数据作为字符串返回:.responseString而不是JSON:.responseJSON

工作代码:

func getDataFromServer() {
Alamofire.request(.POST, websiteURL, parameters: myParameters) .responseJSON {
    (response) -> Void in
    if let value = response.result.value {
        let json = JSON(value)
        self.parseJSON(json)
    }
}
}

答案 3 :(得分:0)

responseString替换为responseJSON

相关问题