I'm new in iOS development, so sorry for stupid question in advance. I have json like this:
{
"type":"post",
"comments":{
"count":0,
"can_post":1
},
"likes":{
"count":0,
"user_likes":0,
"can_like":1,
"can_publish":1
},
"reposts":{
"count":0,
"user_reposted":0
}
}
I want to convert this to class which will contain just likesCount, commentsCount, repostsCount but without creating separate classes for comments, likes, reposts. I'm using Decodable for this and here is my code which doesn't work :)
Code:
final class FeedItem: Decodable {
enum Keys: String, CodingKey {
case type,
likes = "likes.count",
comments = "comments.count",
reposts = "reposts.count"
}
let type: String
var likes = 0
var comments = 0
var reposts = 0
required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
let type = try container.decode(String.self, forKey: .type)
let likes = try container.decode(Int.self, forKey: .likes)
let comments = try container.decode(Int.self, forKey: .comments)
let reposts = try container.decode(Int.self, forKey: .reposts)
self.init(type: type, likes: likes, comments: comments, reposts: reposts)
}
init(type: String,
likes: Int,
comments: Int,
reposts: Int) {
self.type = type
self.likes = likes
self.comments = comments
self.reposts = reposts
}
}
Error:
"No value associated with key Keys(stringValue: \"likes.count\", intValue: nil) (\"likes.count\")."