【发布时间】:2017-03-29 14:06:25
【问题描述】:
嗨,我是新来的 swift 任何想法。如何从 json 对象初始化结构。我不知道我该怎么做。
{ “用户”:{ “名称”:“cruskuaka”, “电子邮件”:“cristlika@gmail.com”, “电话号码”:“018833455” }, “地址”: { “房子”:“100”, “街道”:“B”, “镇”: { "town_id": "1", "town_name": "戈尔韦市中心" }, “城市”: { "city_id": "10", "city_name": "戈尔韦" }, "address_id":"200", "full_address":"100, B, 戈尔韦市中心,戈尔韦" }, "delivery_instruction": "没有电话", “delivery_method”:“1” }
这里都是结构:
struct Contact {
let user : User
let address : Address
let deliveryInstruction : String
let deliveryMethod : String
init(dictionary: [String: Any]) {
self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
self.address = Address(dictionary: dictionary["address"] as? [String:Any] ?? [:])
self.user = User(dictionary: dictionary["address"] as? [String:Any] ?? [:])
}
}
struct User {
let name : String
let email : String
let phoneNo : String
init(dictionary : [String:Any] ) {
self.name = dictionary["name"] as? String ?? ""
self.email = dictionary["email"] as? String ?? ""
self.phoneNo = dictionary["phoneNo"] as? String ?? ""
}
}
struct Address {
let city : City
let town : Town
let addressId : String
let fullAddress : String
let house : String
let street: String
init(dictionary : [String:Any] ) {
self.addressId = dictionary["address_id"] as? String ?? ""
self.fullAddress = dictionary["full_address"] as? String ?? ""
self.house = dictionary["house"] as? String ?? ""
self.street = dictionary["street"] as? String ?? ""
self.city = City(dictionary: dictionary["address"] as? [String:Any] ?? [:])
self.town = Town(dictionary: dictionary["address"] as? [String:Any] ?? [:])
}
}
struct City {
let cityId : String
let cityName : String
init(dictionary : [String:Any] ) {
self.cityId = dictionary["city_id"] as? String ?? ""
self.cityName = dictionary["city_name"] as? String ?? ""
}
}
struct Town {
let townId : String
let townName : String
init(dictionary : [String:Any]) {
self.townId = dictionary["town_id"] as? String ?? ""
self.townName = dictionary["town_name"] as? String ?? ""
}
}
【问题讨论】:
-
Swift 字典的 jsonFormatString 名称非常具有误导性。将其更改为
let contact: [String: Any] = -
@LeoDabus 谢谢.. .. 你能帮我解决吗?任何方式你做它或你流动
-
试试
urlRequest.httpMethod = "POST" urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = jsonData -
@LeoDabus 结果不一样
-
@LeoDabus 我的代码工作正常问题是服务器端.. 非常感谢.. 祝你一切顺利