我很抱歉如果这个问题被回答了很多次,但我正在寻找我自己的特定json问题,这就是为什么我发布这篇文章,这是我的json它是一个通知的数组列表,在额外的对象中你可以看到它有contract对象,现在这个对象正在改变它可以是活动或反馈在json数组的第二个索引中如何使可编码的结构来解码这种类型的jsonHere是我的结构,我不能在可编码中做任何类型
struct Alert: Decodable { var id: Int? var isUnread: Bool? var userId: Int? var message: String? var notificationType: String? var extra: Any?
"value": [
{
"id": 153,
"is_unread": true,
"user_id": 3,
"message": "Contract offered from JohnWick. Click here to see the details.",
"notification_type": "Contract",
"extra": {
"contract": {
"id": 477,
"likes": 0,
"shares": 0,
"account_reach": 0.0,
"followers": 0,
"impressions": 0.0,
"description": "Fsafasd",
"budget": 0.0,
"start_date": null,
"end_date": null,
"status": "pending",
"is_accepted": false,
"brand_id": 443,
"influencer_id": 3,
"proposal_id": 947,
"created_at": "2019-11-09T17:40:57.646Z",
"updated_at": "2019-11-09T17:40:57.646Z",
"contract_fee": 435345.0,
"base_fee": 5000.0,
"transaction_fee": 43534.5,
"total_fee": 483879.5,
"infuencer_completed": false,
"brand_completed": false,
"comments": 0
}
}
},
{
"id": 152,
"is_unread": true,
"user_id": 3,
"message": "Message from JohnWick. Click here to check your inbox.",
"notification_type": "Message",
"extra": {
"message": {
"id": 495,
"body": "Uuhvh",
"read": false,
"conversation_id": 42,
"user_id": 3,
"created_at": "2019-11-08T13:44:02.055Z",
"updated_at": "2019-11-08T13:44:02.055Z"
}
}
},
]正如您所看到的,它可以是消息、活动、合同或反馈,那么我该如何解析它,或者如何使用CodingKeys对其进行建模
发布于 2019-11-10 03:06:17
一个简单的解决方案是创建一个名为Extra的结构,对于您拥有的每种情况,该结构都有四个可选属性。
struct Extra: Codable {
let contract: Contract?
let message: Message?
let feedback: Feedback?
let campaign: Campaign?
}只要消息、活动、合同和反馈中的每一个都有固定的响应,那么您就应该能够为它们创建符合Codable的结构。
发布于 2019-11-10 03:50:38
你不是指Any吧。正如您所说,extra可以是“消息、活动、合同或反馈”。它不能是UIViewController或CBPeripheral。它不是“任何东西”这是四件事中的一件。
"One of X things“是枚举:
enum Extra {
case contract(Contract)
case campaign(Campaign)
case message(Message)
case feedback(Feedback)
}要使其可解码,我们只需查找正确的密钥:
extension Extra: Decodable {
enum CodingKeys: CodingKey {
case contract, campaign, message, feedback
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Try to decode each thing it could be; throw if nothing matches.
if let contract = try? container.decode(Contract.self, forKey: .contract) {
self = .contract(contract)
} else if let campaign = try? container.decode(Campaign.self, forKey: .campaign) {
self = .campaign(campaign)
} else if let message = try? container.decode(Message.self, forKey: .message) {
self = .message(message)
} else if let feedback = try? container.decode(Feedback.self, forKey: .feedback) {
self = .feedback(feedback)
} else {
throw DecodingError.valueNotFound(Self.self,
DecodingError.Context(codingPath: container.codingPath,
debugDescription: "Could not find extra"))
}
}
}发布于 2020-07-22 17:01:53
在本文中,您可以找到一种支持任何类型的方法,因此JSON返回的是String还是Int都无关紧要:
https://stackoverflow.com/questions/58782346
复制相似问题