gpt4 book ai didi

swift - Json 对象映射 Swift

转载 作者:行者123 更新时间:2023-11-28 14:57:20 24 4
gpt4 key购买 nike

我想对 url 发出 Post 请求,但是我刚刚了解到 Swift 中称为对象映射的新概念。我学习了如何将 Json 对象映射到 swift 结构或类的所有教程,但没有告诉我如何在映射后使用这些对象。

我如何访问这些对象,以便在执行发布请求时使用它们。

这是示例 Json:

{
"country": "string",
"dateOfBirth": "string",
"email": "string",
"gender": "string",
"id": "string",
"interaction": {
"deviceOS": "string",
"deviceType": "string",
"interactionLocation": "string",
"interactionType": "string",
"timeStamp": "string"
},
"name": "string",
"occupation": "string",
"passportOrIDimage": "string",
"phoneNumber": "string",
"physicalAddress": "string",
"salutation": "string",
"surname": "string",
"userlogin": {
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"enabled": true,
"password": "string",
"roles": [
{
"roleName": "string"
}
],
"username": "string"
}
}

swift 4 中的对象映射示例:

    struct Register: Codable {
let country: String?
let dateOfBirth: String?
let email: String?
let gender: String?
let id: String?
let interaction: Interaction?
let name: String?
let occupation: String?
let passportOrIDimage: String?
let phoneNumber: String?
let physicalAddress: String?
let salutation: String?
let surname: String?
let userlogin: Userlogin?

enum CodingKeys: String, CodingKey {
case country = "country"
case dateOfBirth = "dateOfBirth"
case email = "email"
case gender = "gender"
case id = "id"
case interaction = "interaction"
case name = "name"
case occupation = "occupation"
case passportOrIDimage = "passportOrIDimage"
case phoneNumber = "phoneNumber"
case physicalAddress = "physicalAddress"
case salutation = "salutation"
case surname = "surname"
case userlogin = "userlogin"
}
}

struct Interaction: Codable {
let deviceOS: String?
let deviceType: String?
let interactionLocation: String?
let interactionType: String?
let timeStamp: String?

enum CodingKeys: String, CodingKey {
case deviceOS = "deviceOS"
case deviceType = "deviceType"
case interactionLocation = "interactionLocation"
case interactionType = "interactionType"
case timeStamp = "timeStamp"
}
}

struct Userlogin: Codable {
let accountNonExpired: Bool?
let accountNonLocked: Bool?
let credentialsNonExpired: Bool?
let enabled: Bool?
let password: String?
let roles: [Role]?
let username: String?

enum CodingKeys: String, CodingKey {
case accountNonExpired = "accountNonExpired"
case accountNonLocked = "accountNonLocked"
case credentialsNonExpired = "credentialsNonExpired"
case enabled = "enabled"
case password = "password"
case roles = "roles"
case username = "username"
}
}

struct Role: Codable {
let roleName: String?

enum CodingKeys: String, CodingKey {
case roleName = "roleName"
}
}

// MARK: Convenience initializers

extension Register {
init(data: Data) throws {
self = try JSONDecoder().decode(Register.self, from: data)
}

init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}

init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}

func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

extension Interaction {
init(data: Data) throws {
self = try JSONDecoder().decode(Interaction.self, from: data)
}

init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}

init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}

func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

extension Userlogin {
init(data: Data) throws {
self = try JSONDecoder().decode(Userlogin.self, from: data)
}

init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}

init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}

func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

extension Role {
init(data: Data) throws {
self = try JSONDecoder().decode(Role.self, from: data)
}

init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}

init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}

func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}

我想把我想发布的数据放在 params 字典中,我不确定如何使用对象映射来做到这一点。

我的发帖请求:

 var request = URLRequest(url: URL(string: "http://testURL")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params as Any, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
let alert = UIAlertController(title: "Response", message: "message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
print(json)
} catch {
print("error")
}
})

task.resume()

}

最佳答案

如果你在你的结构中观察

func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}

在您的发帖请求中,您可以这样使用

request.httpBody = try?  objectOfCodableStruct.jsonData()

希望对你有帮助

关于swift - Json 对象映射 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206313/

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