无法提取JSON

时间:2018-02-21 18:29:14

标签: ios json alamofire

您好我正在尝试提取json。但是我收到错误Cannot convert value of type 'Data' to expected argument type 'NSData'。有什么我做错了吗?

    success: { (response) -> Void in
        var dataStream: Data = Data.init(referencing: response!)
        do {
        let data = try JSONSerialization.jsonObject(with: dataStream, options: JSONSerialization.ReadingOptions.mutableContainers)as AnyObject
        }catch{
        }
        if let id = response!["money"]as? String {
            print(id)
        }

    }){ (error) -> Void in
        print("error")
    }
}

UPDATE2

let request = Alamofire.request(apiUrl, method: .get)


    request.responseJSON { response in
        switch response.result
        {
        case .success:
            success(response.result.value as AnyObject)
        case .failure(let error):
            failure(error as NSError)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你的问题在这里

var dataStream: Data = Data.init(referencing: response!)
文档中的

  

init(引用引用:NSData)

响应应该是NSData类型而不是数据,您可以尝试

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

注意投射到预期的返回它是否是字典或数组

这个

 if let id = response!["money"]as? String {
        print(id)
    }

应替换为

  if let id = responseDict!["money"]as? String {
        print(id)
    }

您可以使用Alamofire

尝试SwiftyJson
        Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
            debugPrint(response)

            if let json = response.data {
                let data = JSON(data: json)
                print("data\(data["money"])")

            }
        }