gpt4 book ai didi

ios - Swift - 无法读取数据,因为它的格式不正确

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:58 24 4
gpt4 key购买 nike

我正在开发一个项目来学习如何解析 JSON。我正在尝试将 JSON 解析为 struct。我正在尝试使用接下来的代码来执行此操作,但出现以下错误:

Err The data couldn’t be read because it isn’t in the correct format.

我做错了什么?我也尝试使用 Alamofire,但我没有找到将其解析为结构的方法。

func getData(){
let gitUrl = URL(string: "http://95.46.99.250:9095/api/v1/institution-categories")
URLSession.shared.dataTask(with: gitUrl!) { (data, response
, error) in
let data = data
print(data)
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode([Root].self, from: data!)

} catch let err {
print("\nErr", err.localizedDescription)
}
}.resume()
}

结构

struct Root: Codable {
let data: [InnerItem]
}
struct InnerItem:Codable {
let id: Int?
let image: String?
let name: String?

private enum CodingKeys : String, CodingKey {
case id = "id", image = "image", name = "name"
}
}

JSON

{
"data": [
{
"id": 1,
"name": "Пабы и бары",
"image": "http://95.46.99.250:9095/storage/photos/beer@2x.png"
},
{
"id": 2,
"name": "Кафе",
"image": "http://95.46.99.250:9095/storage/photos/coffee@3x.png"
},
{
"id": 3,
"name": "Ночной клуб",
"image": "http://95.46.99.250:9095/storage/photos/0201f7523bc2028f174710b51379e432.png"
},
{
"id": 4,
"name": "Ресторан",
"image": "http://95.46.99.250:9095/storage/photos/restaurants@3x.png"
},
{
"id": 5,
"name": "Караоке-клуб",
"image": "http://95.46.99.250:9095/storage/photos/microphone.png"
},
{
"id": 6,
"name": "Суши-бар",
"image": "http://95.46.99.250:9095/storage/photos/sushi.png"
},
{
"id": 7,
"name": "Пиццерии",
"image": "http://95.46.99.250:9095/storage/photos/pizza.png"
},
{
"id": 8,
"name": "Кальянная",
"image": "http://95.46.99.250:9095/storage/photos/c111d1e5ad6b90b61ac36836d220ebba.png"
},
{
"id": 9,
"name": "Общая",
"image": "http://95.46.99.250:9095/storage/photos/Group 315@3x.png"
}
]
}

最佳答案

💡 解决编码/解码错误

当使用 codable 时,不要打印 .localizedDescription,而是尝试打印出 error 本身!所以编译器描述了问题的确切位置!

do {
let decoder = JSONDecoder()
let decoded = try decoder.decode([Root].self, from: data!)
} catch {
// print(error.localizedDescription) // <- ⚠️ Don't use this!

print(String(describing: error)) // <- ✅ Use this for debuging!
}

在你的情况下

它会指出:

  • 解码器尝试将根对象解码为Array,但发现了一个Dictionary

所以你关注这个问题,发现你应该替换:

decoder.decode([Root].self, from: data!)

与:

decoder.decode(Root.self, from: data!)

关于ios - Swift - 无法读取数据,因为它的格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51386257/

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