HI i am new to swift any idea . How to initialize a struct from a json object . i could not figure out how can i do it .
{ "user": { "name": "cruskuaka", "email": "cristlika@gmail.com", "phoneNo":"018833455" }, "address": { "house": "100", "street": "B", "town": { "town_id": "1", "town_name": "Galway city center" }, "city": { "city_id": "10", "city_name": "Galway" }, "address_id":"200", "full_address":"100, B, Galway city center,Galway" }, "delivery_instruction": "no call", "delivery_method": "1" }
Here all struct :
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 ?? ""
}
}
You have more than one error in your code, but you are in the right path. You are using the wrong key when initializing your user, city and town structs. I have also created two more initializers so you can initialize your struct with a dictionary, the json string or just its data:
Testing the initialization from JSON: