gpt4 book ai didi

swift4 - 如何使用 Swift 4 编码键处理来自 json 响应的动态键

转载 作者:行者123 更新时间:2023-12-04 03:00:36 24 4
gpt4 key购买 nike

在我的应用程序中,我得到这样的响应,我将如何处理这种在每个数据数组中都有动态键的响应

{
"code": 200,
"message": "Top Likers info.",
"error": null,
"data": {
"manishamohapatra11": {
"id": "5591322611",
"username": "manishamohapatra11",
"full_name": ":-)Sunshine :-)",
"profile_pic_url": "https://scontent-atl3-1.cdninstagram.com/vp/d2ba431ac70ec067d5d6def73a721250/5B553C8E/t51.2885-19/s150x150/27877706_168319037141873_8387886458379173888_n.jpg",
"followed_by_viewer": true,
"requested_by_viewer": false,
"likeCount": 7
},
"chrysxnthemxm": {
"id": "5658970660",
"username": "chrysxnthemxm",
"full_name": "Quotes and Sayings",
"profile_pic_url": "https://scontent-atl3-1.cdninstagram.com/vp/f1fb37c94c181d49d9997e24b5d70068/5B40EF01/t51.2885-19/s150x150/20478547_331538517270771_7021810425566068736_a.jpg",
"followed_by_viewer": true,
"requested_by_viewer": false,
"likeCount": 4
}
}
}

我已经创建了结构响应

最佳答案

// A struct that conforms to the CodingKey protocol
// It defines no key by itself, hence the name "Generic"
struct GenericCodingKeys: CodingKey {
var stringValue: String
var intValue: Int?

init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
}

struct Response: Decodable {

// Define the inner model as usual
struct User: Decodable {
var id: String
var userName: String
var fullName: String
var profilePicURL: URL
var followedByViewer: Bool
var requestedByViewer: Bool
var likeCount: Int

private enum CodingKeys: String, CodingKey {
case id
case userName = "username"
case fullName = "full_name"
case profilePicURL = "profile_pic_url"
case followedByViewer = "followed_by_viewer"
case requestedByViewer = "requested_by_viewer"
case likeCount
}
}

var code: Int
var message: String
var error: String?
var users: [User]

private enum CodingKeys: String, CodingKey {
case code, message, error, data
}

// You must decode the JSON manually
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.code = try container.decode(Int.self, forKey: .code)
self.message = try container.decode(String.self, forKey: .message)
self.error = try container.decodeIfPresent(String.self, forKey: .error)

self.users = [User]()
let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .data)
for key in subContainer.allKeys {
let user = try subContainer.decode(User.self, forKey: key)
self.users.append(user)
}
}
}

关于swift4 - 如何使用 Swift 4 编码键处理来自 json 响应的动态键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49549691/

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