2017-01-03 64 views
0

我是swift 3和alamofire的新手。如何从JSON API中获取值到类变量中

需要帮助来解析对变量的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] 

的响应可以有人帮助我怎么能得到项目和UPC的值到一个局部变量。

回答

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 
+0

由于阿南德,它完美。非常感谢。 – Uyyan

+0

来吧@Uyyan。 –