我正在使用如下所示的Json服务器响应数据我使用模型类获得了所有键值对,并且无法只获得一个键值对街道任何人都可以帮助我如何获取街道键值对吗?
这是我的Json数据
{
"address": {
"city": "chennai",
"firstname": "sommesh",
"lastname": "s",
"email": "test@gmail.com",
"postcode": "43",
"street": [
"[No: 14; 8th cross street]"
],
"country_id": "US",
"region_code": "CA",
"region_id": "12",
"telephone": "8756467654",
"sameAsBilling": 1,
"region": "California",
"prefix": "",
"company": "Test Company"
}
}
这是我的模型类代码
struct GuestAddress {
let id : Int
let region : String
let regionId : Any
let regionCode : String
let countryId : String
let company : String
let telephone : Any
let postCode : Any
let city : String
let firstName : String
let lastName : String
let email : String
let sameAsBilling : Any
let saveInAddressBook : Any
var street : [String]
init(dict : [String:Any]) {
self.id = dict["id"] as! Int
self.region = dict["region"]! as! String
self.regionId = dict["region_id"]!
self.regionCode = dict["region_code"]! as! String
self.countryId = dict["country_id"]! as! String
self.company = dict["company"]! as! String
self.telephone = dict["telephone"]! as! String
self.postCode = dict["postcode"]!
self.city = dict["city"]! as! String
self.firstName = dict["firstname"]! as! String
self.lastName = dict["lastname"]! as! String
self.email = dict["email"]! as! String
self.sameAsBilling = dict["same_as_billing"]!
self.saveInAddressBook = dict["save_in_address_book"]!
let guestStreet = dict["street"] as! [String]
var streetArr = street
for item in guestStreet {
streetArr.append(item)
}
street = streetArr
}
}
答案 0 :(得分:1)
首先初始化变量
var street:[String] = []
因为在这里,你宣布了
var street:[String]
从未初始化, 在你写完之后
var streetArr = street
这意味着“streetArr”也没有初始化。所以
streetArr.append(项目) 什么都不做。
答案 1 :(得分:0)
你有多余的代码工作。
更正如下:
var street : [String] = []
init(dict : [String:Any]) {
:
:
:
:
let guestStreet : [String] = dict["street"] as! [String] //2. here, guestStreet is the array of address.
// 3. Print guestStreet
//[ "[No: 14; 8th cross street]" ]
// get required result
for item in guestStreet {
var address = item
address.remove(at: address.startIndex) //4. remove first brace
address = String(address.characters.dropLast()) //5. remove last brace
street.append(address) //6. Append address
}
print(street.first!) //7. Output
多数民众赞成。
<强>输出:强>