-1

How to manually decode [Album] and [Image] by keys ? I tried, but I can not. I do not know what the error is? Thank you ! My Json http://appscorporation.ga/api-user/test

struct ProfileElement: Codable {
    let user: User

    let postImage: String
    let postLikes: Int
    let postTags: String

    enum CodingKeys: String, CodingKey {
        case user

        case postImage = "post_image"
        case postLikes = "post_likes"
        case postTags = "post_tags"
    }
}

struct User: Codable {
    let name, surname: String
    let profilePic: String
    let albums: [Album]

    enum CodingKeys: String, CodingKey {
        case name, surname
        case profilePic = "profile_pic"
        case albums
    }
}

second blok

struct Album {
    let id: Int
    let title: String
    var images: [Image]
    enum AlbumKeys: String, CodingKey {
        case id = "id"
        case title = "title"
        case images = "images"
    }
}
struct Image: Codable {
    let id: Int
    let url: String

    enum CCodingKeys: String, CodingKey {
        case id = "id"
        case url = "url"
    }
} 
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Album is not conforming to Codable? and misspelling of "CCodingKeys" in Image. And "AlbumKeys". – meggar Feb 01 '19 at 15:42

1 Answers1

0

You get the error

Type 'User' does not conform to protocol 'Decodable'

Because all structs have to adopt (De)codable,

The structs work if you make litte changes

struct ProfileElement: Decodable {
    let user: User

    let postImage: String
    let postLikes: Int
    let postTags: String
}

struct User: Decodable {
    let name, surname: String
    let profilePic: String
    let albums: [Album]
}

struct Album : Decodable {
    let id: Int
    let title: String
    var images: [Image]

}
struct Image: Decodable {
    let id: Int
    let url: String
}

then decode

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase // This line gets rid of all CodingKeys
let result = try decoder.decode([ProfileElement].self, from: data)

and you can get each image with

for item in result {
    for album in item.user.albums {
        for image in album.images {
            print(image)
        }
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361