如何在 swift 3 中解析 alamofire json 响应?



我是Swift编程的新手,我花了相当多的时间弄清楚如何解析来自Alamofire服务器调用的JSON响应。我的 Json 响应是

{"customer_info":[{"customer_id":"147","response_code":1}]}

我想访问这两个变量。我的快速代码是

Alamofire.request(
URL_USER_REGISTER,
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).responseJSON
{

if let json = response.result.value {
print (json)
}
if let result = response.result.value as? [String:Any] {
var names = [String]()

do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let blogs = json["customer_info"] as? [[String: Any]] {
for blog in blogs {
if let name = blog["customer_id"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: (error)")
}
print(names)


}
}

请帮忙

您的代码解析正确。将以下代码添加到您的博客循环中并取出第二个变量

if let response_code = blog["response_code"] as? Int {
//Do something here
}

所以你正在寻找的完整代码是

let str = "{"customer_info":[{"customer_id":"147","response_code":1}]}"
let data = str.data(using: .utf8)
do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let blogs = json["customer_info"] as? [[String: Any]] {
for blog in blogs {
if let name = blog["customer_id"] as? String {
print(name)
}
if let response_code = blog["response_code"] as? Int {
print(response_code)
}
}
}
} catch {
print("Error deserializing JSON: (error)")
}

我已经修改了代码并立即获得结果

if let jsonDict = response.result.value as? [String:Any],
let dataArray = jsonDict["customer_info"] as? [[String:Any]]
{
let nameArray = dataArray.flatMap { $0["customer_id"] as? String }
let nameArray2 = dataArray.flatMap { $0["response_code"] as? Int }
if(dataArray.count>0)
{
//store return customer id and response code
let customer_id_received = nameArray[0]
let response_code_received = nameArray2[0]
if(response_code_received==1)
{
//proceed with storing customer id in global variable
print(nameArray2[0])
}

最新更新