gpt4 book ai didi

swift - 在 swift 中映射嵌套的 JSON Realm 对象

转载 作者:可可西里 更新时间:2023-11-01 01:56:11 24 4
gpt4 key购买 nike

我正在使用 Realm 和 Alamofire 来获取和存储我的数据,但是我得到了一个对象,它是一个嵌套的 JSON 对象我正在尝试访问地址但我得到的是 nil 我能够获取内容数据但不能地址

“内容”:[ { “编号”:1, "名字": "姓名", “姓氏”:“姓氏” “地址”: { “编号”:1, “城市”:“城市”, “电话”:空, “街道”:“城市”,

class Name: Object, Mappable {
@objc dynamic var id: Int = 0
@objc dynamic var fisrtname: String? = ""
@objc dynamic var lastname: String? = ""
@objc dynamic var Address: Address? = nil
override static func primaryKey() -> String? {
return "id"
}

required convenience init?(map: Map) {
self.init()
}

func mapping(map: Map) {
id <- map["id"]
fisrtname <- map["fisrtname"]
lastname <- map["lastname"]
Address <- map["Address"]
}

class Address: Object {
@objc dynamic var id: Int = 0
@objc dynamic var city: String? = ""
@objc dynamic var phone: Int? = ""
@objc dynamic var street: String? = ""

override static func primaryKey() -> String? {
return "id"
}

required convenience init?(map: Map) {
self.init()
}

func mapping(map: Map) {
id <- map["id"]
city <- map["city"]
phone <- map["phone"]
street <- map["street"]

}
}

最佳答案

尝试制作这样的模型

import Foundation
import RealmSwift

class Name: Object {
dynamic var id = 0
dynamic var fisrtname : String?
dynamic var lastname : String?
dynamic var Address : UserAddress? = UserAddress()

override static func primaryKey() -> String? {
return "id"
}
}


class UserAddress: Object {

dynamic var id = 0
dynamic var city : String?
dynamic var phone : String?
dynamic var street : String?

override static func primaryKey() -> String? {
return "Id"
}
}

然后从 Json 获取地址:

let responseResult = result["Result"] as! NSDictionary
let name = Name(value: responseResult)
let address = name.Address?.city

关于swift - 在 swift 中映射嵌套的 JSON Realm 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53203080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com