[英]How to store the JSON data into array(model class) in swift3?
[英]Store JSON data into model class array in Swift 4
我想將獲取的JSON數據存儲到我的模型類數組propertyArray中。 一些我如何使用Alamofire庫獲取JSON數據,現在我想將該數據解析為PropertyList模型類的屬性。 我無法將JSON數據解析為propertyArray。 關於堆棧溢出,我提到了許多其他解決方案,但沒有得到任何合適的解決方案。
聲明的模型類數組
var propertyArray: [PropertyList]? = []
Alamofire功能
func dataPass() {
print("Landlord id is \(land.id)")
let para: Parameters = ["id": land.id]
Alamofire.request(URL_Landlord_Property_List, method: .post, parameters: para).responseJSON { response in
if let dictionary = response.result.value as? [String : AnyObject]{
var prop = PropertyList()
let data = dictionary["data"] as! [Any]
print(data)
}
}
}
對propertyList
import Foundation
struct PropertyList{
var property_id: String?
var user_id: String?
var property_code: String?
var property_added_date: String?
var property_updated_date: String?
var property_termination_date: String?
var property_ASYS_no: String?
var propertyCode: String?
var property_address_1:String?
var property_address_2: String?
var property_address_3: String?
var property_city: String?
var property_cluster:String?
var property_area:String?
var property_postcode: String?
var property_landlord_ref_code: String?
var property_landlord_id: String?
}
JSON數據
{
"success": true,
"data": [
{
"property_id": "1",
"user_id": "1",
"property_code": "0001",
"property_added_date": "2017-12-13",
"property_updated_date": "2017-12-13 00:00:00",
"property_termination_date": null,
"property_ASYS_no": "ASYS 001",
"propertyCode": "0001-PUNE1",
"property_address_1": "PUNE1",
"property_address_2": "PUNE2",
"property_address_3": "PUNE3",
"property_city": "PUNE",
"property_cluster": "1",
"property_area": "1",
"property_postcode": "424031",
"property_landlord_ref_code": null,
"property_landlord_id": "1"
},
{
"property_id": "2",
"user_id": "1",
"property_code": "0002",
"property_added_date": "2017-12-14",
"property_updated_date": "2017-12-18 00:00:00",
"property_termination_date": null,
"property_ASYS_no": "asys 0200",
"propertyCode": "0002-hadpasar1",
"property_address_1": "hadpasar1",
"property_address_2": "hadpasar2",
"property_address_3": "hadpasar3",
"property_city": "pune",
"property_cluster": "9",
"property_area": "2",
"property_postcode": "012121",
"property_landlord_ref_code": null,
"property_landlord_id": "1"
}
]
}
看起來您的JSON是一個包含字典的數組。 (鍵值數據結構)
這應該可以解決問題。
let data = dictionary["data"] as! [[String: Any]]
然后在構造函數中解析它:
struct PropertyList{
init(dict: [String: Any){
//parse here...
self.property_id = dict["property_id"] as! String
}
}
要添加到數組:
for dict in data{
let propertyList = PropertyList(dict: dict)
propertyArray.append(propertyList)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.