gpt4 book ai didi

json - 无法使用 JSONDecoder 解码

转载 作者:搜寻专家 更新时间:2023-11-01 06:28:31 27 4
gpt4 key购买 nike

如何使用 JSONDecoder 解码此 JSON?我正在尝试,但我总是以崩溃告终。我有另一篇文章在谈论它,但之前错误更大,现在我只停留在上面。我也尝试过使用 JSONSerialization,但我认为使用 JSONDecoder 更干净。

当编译器通过 JSONDecoder 部分时,我收到此错误消息:

Could not get API data. typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil)), The data couldn’t be read because it isn’t in the correct format.

这就是我尝试解析所有数据的方式:

import Foundation

//typealias AudiobookJSON = [[String: Any]]

struct APIClient {

static func getAudiobooksAPI(completion: @escaping ([Audiobook]?) -> Void) {

let url = URL(string: "https://alodjinha.herokuapp.com/categoria")

let session = URLSession.shared

guard let unwrappedURL = url else { print("Error unwrapping URL"); return }

let dataTask = session.dataTask(with: unwrappedURL) { (data, response, error) in

guard let unwrappedDAta = data else { print("Error unwrapping data"); return }

do {


let posts = try JSONDecoder().decode([Audiobook].self, from: unwrappedDAta)

print(posts)


completion(nil)

} catch {
print("Could not get API data. \(error), \(error.localizedDescription)")
}
}
dataTask.resume()
}
}

我正在使用的结构:

import Foundation

struct Data : Decodable {

let data : [Audiobook]
}

struct Audiobook: Decodable {
let id : Int?
let descricao : String?
let urlImagem : String?

// init(dictionary: Audiobook) {
// self.descricao = dictionary["descricao"] as! String
// self.urlImagem = dictionary["urlImagem"] as! String
//
// }
}

待解析的 JSON:

{
"data": [
{
"id": 1,
"descricao": "Games",
"urlImagem": "http:\/\/39ahd9aq5l9101brf3b8dq58.wpengine.netdna-cdn.com\/wp-content\/uploads\/2013\/06\/3D-Gaming.png"
},
{
"id": 2,
"descricao": "Livros",
"urlImagem": "http:\/\/4.bp.blogspot.com\/-6Bta1H9d22g\/UJAIJbqcHhI\/AAAAAAAAKi4\/hvgjWrlFc64\/s1600\/resenha-missiologia.png"
},
{
"id": 3,
"descricao": "Celulares",
"urlImagem": "http:\/\/pt.seaicons.com\/wp-content\/uploads\/2015\/11\/Mobile-Smartphone-icon.png"
},
{
"id": 4,
"descricao": "Inform\u00e1tica",
"urlImagem": "http:\/\/portal.ifrn.edu.br\/campus\/ceara-mirim\/noticias\/ifrn-oferece-curso-de-informatica-basica-para-pais-dos-estudantes\/image_preview"
},
{
"id": 5,
"descricao": "Eletrodom\u00e9stico",
"urlImagem": "http:\/\/classificados.folharegiao.com.br\/files\/classificados_categoria\/photo\/8\/sm_4d5ed3beb0f31b61cb9a01e46ecd0cf9.png"
},
{
"id": 6,
"descricao": "TVs",
"urlImagem": "http:\/\/i.utdstc.com\/icons\/256\/terrarium-tv-android.png"
},
{
"id": 7,
"descricao": "Filmes e S\u00e9ries",
"urlImagem": "https:\/\/pbs.twimg.com\/profile_images\/801033586438733824\/91Y_N91t_reasonably_small.jpg"
},
{
"id": 8,
"descricao": "M\u00f3veis e Decora\u00e7\u00f5es",
"urlImagem": "https:\/\/image.flaticon.com\/icons\/png\/128\/148\/148188.png"
},
{
"id": 9,
"descricao": "Moda, Beleza e Perfumaria",
"urlImagem": "http:\/\/icon-icons.com\/icons2\/196\/PNG\/128\/fashion_23852.png"
},
{
"id": 10,
"descricao": "Papelaria",
"urlImagem": "http:\/\/esen.pt\/in\/images\/stories\/skills_256.png"
}
]
}

最佳答案

当数据实际上是一个包装数组的字典时,您正试图将其解码为 [AudioBook],如在您的 Data 结构中。只需将其更改为:

let data = try JSONDecoder().decode(Data.self, from: unwrappedDAta)

你应该可以开始了。

关于json - 无法使用 JSONDecoder 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595745/

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