Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在swift 4中手动解码json数据_Json_Swift_Xcode_Parsing_Codable - Fatal编程技术网

如何在swift 4中手动解码json数据

如何在swift 4中手动解码json数据,json,swift,xcode,parsing,codable,Json,Swift,Xcode,Parsing,Codable,如何通过按键手动解码[相册]和[图像]? 我试过了,但不行。 我不知道错误是什么? 非常感谢。 我的Json 第二个blok struct Album { let id: Int let title: String var images: [Image] enum AlbumKeys: String, CodingKey { case id = "id" case title = "title" case imag

如何通过按键手动解码[相册]和[图像]? 我试过了,但不行。 我不知道错误是什么? 非常感谢。 我的Json

第二个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"
    }
} 
你得到了错误

类型“User”不符合协议“Decodable”

因为所有结构都必须采用
(De)codable

只要稍作修改,结构就可以工作

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
}
然后解码

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

for item in result {
    for album in item.user.albums {
        for image in album.images {
            print(image)
        }
    }
}

相册不符合Codable?以及图像中“CCodingKeys”的拼写错误。和“相册钥匙”。
for item in result {
    for album in item.user.albums {
        for image in album.images {
            print(image)
        }
    }
}