如何从 JSON 对象初始化一个结构体

8

你好,我是新手 Swift 开发者,请问如何从 JSON 对象初始化一个结构体?我不知道该怎么做。

{ "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" }

这里是所有的结构体:

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 ?? ""
    }
} 

jsonFormatString 是给 Swift 字典命名非常误导性的名称。请将其更改为 let contact: [String: Any] = - Leo Dabus
@LeoDabus 谢谢..你能帮我解决一下吗?无论你是怎么做的还是在跟随流程。 - user7166107
尝试 urlRequest.httpMethod = "POST" urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = jsonData - Leo Dabus
让我们在聊天中继续这个讨论 - user7166107
1
@LeoDabus,我的代码运行良好,问题出在服务器端...非常感谢你...祝你一切顺利。 - user7166107
显示剩余5条评论
1个回答

11

编辑/更新:在 Swift 4 或更高版本中,您可以使用 Codable 协议:

struct Root: Codable {
    let user: User
    let address: Address
    let deliveryInstruction, deliveryMethod: String
}

struct Address: Codable {
    let house, street, addressId, fullAddress: String
    let town: Town
    let city: City
}

struct City: Codable {
    let cityId, cityName: String
}

struct Town: Codable {
    let townId, townName: String
}

struct User: Codable {
    let name, email, phoneNo: String
}

extension Decodable {
    init(data: Data, using decoder: JSONDecoder = .init()) throws {
        self = try decoder.decode(Self.self, from: data)
    }
    init(json: String, using decoder: JSONDecoder = .init()) throws {
        try self.init(data: Data(json.utf8), using: decoder)
    }
}

别忘了将JSONDecoder属性keyDecodingStrategy设置为.convertFromSnakeCase


let json = """
{"user": {"name": "crst","email": "crat@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" }
"""

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try decoder.decode(Root.self, from: Data(json.utf8))
    print(root)
} catch {
    print(error)
}

或者简单地说:

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let root = try Root(json: json, using: decoder)  // or  Root(data: data, using: decoder) 
    print(root)
} catch {
    print(error)
}

这将打印出来

根(user: __lldb_expr_112.用户(姓名: "cruskuaka", 电子邮件: "cristlika@gmail.com", 电话号码: "018833455"), 地址: __lldb_expr_112.地址(房屋: "100", 街道: "B", 地址Id: "200", 完整地址: "100, B, Galway city center,Galway", 城镇: __lldb_expr_112.城镇(城镇Id: "1", 城镇名: "Galway city center"), 市: __lldb_expr_112.城市(城市Id: "10", 城市名: "Galway")), 交货说明: "不要打电话", 送货方式: "1")



原回答(Codable协议之前)

Swift 3

你的代码中有多个错误,但你正在正确的路径上。在初始化用户、城市和城镇结构时,你使用了错误的键。我还创建了另外两个初始化器,以便你可以使用字典、json字符串或数据来初始化你的结构体:

struct Contact: CustomStringConvertible  {
    let user: User
    let address: Address
    let deliveryInstruction: String
    let deliveryMethod: String
    // customize the description to your needs
    var description: String { return "\(user.name) \(deliveryInstruction) \(deliveryMethod)" }
    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["user"] as? [String: Any] ?? [:])
    }
    init?(data: Data) {
        guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
        self.init(dictionary: json)
    }
    init?(json: String) {
        self.init(data: Data(json.utf8))
    }

}

struct User: CustomStringConvertible {
    let name: String
    let email: String
    let phone: String
    let description: String
    init(dictionary: [String: Any]) {
        self.name = dictionary["name"] as? String ?? ""
        self.email = dictionary["email"] as? String ?? ""
        self.phone = dictionary["phoneNo"] as? String ?? ""
        self.description = "name: \(name) - email: \(email) - phone: \(phone)"
    }
}

struct Address: CustomStringConvertible  {
    let id: String
    let street: String
    let house: String
    let city: City
    let town: Town
    let description: String
    init(dictionary: [String: Any] ) {
        self.id = dictionary["address_id"] as? String ?? ""
        self.description = dictionary["full_address"] as? String ?? ""
        self.house = dictionary["house"] as? String ?? ""
        self.street = dictionary["street"] as? String ?? ""
        self.city = City(dictionary: dictionary["city"] as? [String: Any] ?? [:])
        self.town = Town(dictionary: dictionary["town"] as? [String: Any] ?? [:])
    }
}

struct City: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any] ) {
        self.id = dictionary["city_id"] as? String ?? ""
        self.name = dictionary["city_name"] as? String ?? ""
    }
    
}

struct Town: CustomStringConvertible {
    let id: String
    let name: String
    // customize the description to your needs
    var description: String { return name }
    init(dictionary: [String: Any]) {
        self.id = dictionary["town_id"] as? String ?? ""
        self.name = dictionary["town_name"] as? String ?? ""
    }
}

测试从JSON初始化:

let contact = Contact(json: json)   // crst no call 1

contact               // crst no call 1
contact?.user         // name: crst - email: crat@gmail.com - phone: 018833455
contact?.user.name    //  "crst"
contact?.user.email   //  "crat@gmail.com"
contact?.user.phone   //  "018833455"
contact?.address      //  100, B, Galway city center,Galway
contact?.address.id           //  200
contact?.address.street       //  B
contact?.address.town         // Galway city center
contact?.address.city         //  Galway
contact?.deliveryInstruction  // "no call"
contact?.deliveryMethod       //    1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接