我是swift 3和alamofire的新手。
需要帮助来解析对变量的JSON响应。
func alamofireGet() {
let todoEndpoint: String = "http://54.244.108.186:4000/api/item_upc"
Alamofire.request(todoEndpoint)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling POST on /todos/1")
print(response)
print(response.result.error!)
return
}
// make sure we got some JSON since that's what we expect
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
// get and print the title
guard let todoTitle = json["ITEM"] as? String else {
print(json)
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
}
}
以下是json的回应
["item_upc": <__NSArrayI 0x170245ee0>(
{
ITEM = 458698;
UPC = 14721632;
},
{
ITEM = 458766;
UPC = 14721649;
},
{
ITEM = 458782;
UPC = 14724862;
},
{
ITEM = 458800;
UPC = 14723070;
}
)
, "Error": 0, "Message": Success]
有些人可以帮助我将item和upc的值变为局部变量。
答案 0 :(得分:0)
您可以从JSON获取这样的值: -
//Response from server
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
// here you will get array of itemupc
let itemUPC = json?["item_upc"] as? [[String: Any]] ?? []
// then you can get values as per need can take all values
//inside array or whatever you needed can get with index number
let item = itemUPC?[0]["ITEM"] as? Int ?? 0
let upc = itemUPC?[0]["UPC"] as? Int ?? 0
print("\(item) with upc \(upc)")
输出: -
458698 with upc 14721632