嗨,我是新手,想尽办法。如何从json对象初始化结构。我不知道该怎么办。
{“用户”:{“名称”:“ cruskuaka”,“电子邮件”:“ cristlika@gmail.com”,“电话号码”:“
018833455”},“地址”:{“房屋”:“ 100”,“街道“:” B“,”镇“:{” town_id“:” 1“,”
town_name“:”高威市中心“},” city“:{” 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 4或更高版本,您可以使用可编码协议:
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)
}
这将打印
根(用户: lldb_expr_112.User(名称:“ cruskuaka”,电子邮件:“
cristlika@gmail.com”,电话号码:“ 018833455”)),地址:
lldb_expr_112.Address(房屋:“
100”,街道:“ B”,addressId :“ 200”,完整地址:“ 100,B,戈尔韦市中心,戈尔韦”,镇:
lldb_expr_112.Town(townId:“ 1”,townName:“戈尔韦市中心”),城市:
lldb_expr_112.City(cityId:“ 10 “,cityName:” Galway“)),deliveryInstruction:”
no call“,deliveryMethod:” 1“)
原始答案(在可编码协议之前)
迅捷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
问题内容: 我从AJAX调用REST服务器收到一个JSON对象。该对象具有与我的TypeScript类匹配的属性名称 初始化它的最佳方法是什么?我认为这行不通,因为类(和JSON对象)具有作为对象列表的成员和作为类的成员,而这些类具有作为列表和/或类的成员。 但是我更喜欢一种查找成员名称并在其间进行分配,创建列表并根据需要实例化类的方法,因此,我不必为每个类中的每个成员编写明确的代码(有很多!)
问题内容: 我只是看了这个SO Post: 但是,哥伦比亚大学教授的笔记按以下方式进行。请参阅第9页。 哪种方法正确?他们似乎在说不同的话。 特别是在注释版本中没有。 问题答案: 这根本不会在Java中编译(因为您正在将数组类型的值分配给非数组类型的变量): 被以下错误拒绝(另请参见:http : //ideone.com/0jh9YE): 要进行编译,请声明其类型,然后在其上循环:
我正在尝试初始化CLLocationCoordinate2D,但收到错误: 错误:执行中断,原因:信号SIGABRT。进程已经留在它被中断的地方,使用“thread return-x”返回到表达式求值之前的状态。 不知道我做错了什么。下面是我尝试的:
问题内容: 我在用Java工作。 我通常会这样设置一些对象: 问题是:在此示例中是否等于,按原样我可以假定对未初始化的对象进行空检查将是准确的? 问题答案: 正确,未显式初始化的引用类型的静态成员和实例成员都由Java 设置为。相同的规则适用于数组成员。 根据Java语言规范的第4.12.5节: 变量的初始值 程序中的每个变量在使用值之前都必须具有一个值: 每个类变量,实例变量或数组组件在创建时均
问题内容: 我在创建ThreadLocal并使用new ThreadLocal对其进行初始化时遇到问题。问题是,从概念上讲,我真的只是想要一个持久列表,该列表可以延续线程的寿命,但是我不知道是否有一种方法可以在Java中初始化每个线程的内容。 例如,我想要的是这样的: 这样就可以为每个线程初始化它。我知道我可以这样做: 但我真的不想在每次使用时都进行检查。我能在这里做得更好吗? 问题答案: 您只需
我无法初始化列表,如以下代码所示: 我面临以下错误: 无法实例化类型 如何实例化?