gpt4 book ai didi

iOS swift JSON 到类对象

转载 作者:行者123 更新时间:2023-11-29 01:18:37 26 4
gpt4 key购买 nike

当 JSON 有多个数组时,如何将 JSON 解析为一个类?我正在尝试将数据从 REST API 转换为我在 Swift 2.0 中的类,但我不知道如何正确地进行,有人可以提供帮助吗?

/* JSON from REST API
{
"Name": "New name",
"Email": "test@test.com",
"FacebookId": "new facebook Id",
"Address": "New Address",
"Photo": "https://graph.facebook.com/novo facebook Id/picture?width=500&height=500",
"CreditCards": [
{
"Id": 5,
"LastNumber": "3123",
"Brand": "visa"
},
{
"Id": 6,
"LastNumber": "3124",
"Brand": "visa"
}
]
}

swift 中的类表示?

    class Client {
var fullName: String?
var email: String?
var facebookId: String?
var photo: String?
var creditCards: [CreditCard]?

required init(json: JSON) {
self.fullName = json["FullName"].string
self.email = json["Email"].string
self.facebookId = json["FacebookId"].string
self.photo = json["Photo"].string
self.creditCards = json["CreditCards"]["Id"]
}

required init() {}
}

class CreditCard {
var Id: Int?
var lastNumber: String?
var brand: String?
}

最佳答案

您应该看看 NSJSONSerialization 类及其方法。它们完全满足您的需求:将 JSON 数据转换为数组、字典、字符串和数字。

关于iOS swift JSON 到类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34863881/

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