我有以下JSON,它是当参数occupation
是POST时生成的:
[
{
"group": "GR2923",
"number": "0239039",
}
]
我需要在Swift中解析这些数据,并将group
的值分配给变量groupValue
,将number的值分配给变量numberValue
。
我尝试过使用类似的方法,但我不知道如何将我的JSON数组实现到Alamofire:中
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.data != nil {
let json = JSON(data: response.data!)
let name = json["group"][0][""].string
if name != nil {
print(name!)
}
}
}
发布于 2020-01-20 20:32:01
你可以试试这个:
Alamofire.request(url, method: .get)
.responseJSON { response in
if let value = response.value {
let json = JSON(value).arrayValue
if let name = json[0]["group"].string {
print(name!)
}
}
}
对于使用params的post请求,可以使用以下方法
func getResult(url:String, paramKey:[String], paramValue:[Any], completion: @escaping (Bool, Any?) -> Void) {
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = getParams(paramKey: paramKey, paramValue: paramValue)
guard let url = URL(string: url) else {
completion(false, nil)
return
}
Alamofire.request(url,
method: .post,
parameters: params, encoding: URLEncoding.httpBody , headers: _headers)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
completion(false, nil)
return
}
if let value = response.result.value{
let json = JSON(value)
if json["status_code"].stringValue == "200" {
completion(true, json)
} else {
completion(false, json)
}
}
}
}
func getParams(paramKey:[String], paramValue:[Any]) -> [String:Any] {
var dictionary = [String:Any]()
dictionary.updateValue(Constants.API_TOKEN, forKey: HTTPParams.PARAM_API_TOKEN)
for index in 0..<paramKey.count {
dictionary.updateValue(paramValue[index], forKey: paramKey[index])
}
return dictionary
}
从ViewController,您可以使用这个调用
let url = "Your API Url"
let params = ["occupation"] // Param key
let paramValues = ["doctor"] // Param values
// UrlRequest the file name where the method is placed
UrlRequest().getResult(url: url, paramKey: params, paramValue: paramValues) { (success, data) in
if success {
// Success result with data
}else{
// Failed
}
}
发布于 2020-01-20 22:23:01
您可以使用它来解析json。首先,您必须检查json值是否为NSDictionary。
Alamofire.request(stringURL, method: .get)
.responseJSON { response in
if let value = response.result.value as? NSDictionary {
// print(value)
if let group = value["group"] as? String {
// print(group)
}
}
}
https://stackoverflow.com/questions/59834165
复制相似问题