2017-01-03 14 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] 

iはローカル変数に項目や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

よく来て@ユヤン。 –

関連する問題