我正在开发一个项目来学习如何解析JSON。我正在尝试将JSON解析为结构。我正试图使用接下来的代码来做这件事,但我得到了以下错误:
Err由于数据格式不正确,无法读取数据。
我做错了什么?我也尝试过使用Alamofire,但并没有找到将其解析为struct的方法。
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"
}
]
}
💡coding
/decoding
错误疑难解答
使用codable
s时,不要打印.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!)
试试这个
let gitData = try decoder.decode(Root.self, from: data!)
遍历您的数据
for singleData in gitData.data where (singleData.name ?? "") == "Cafe" {
print(singleData.image)
}
对我来说;无法读取数据,因为它的格式不正确"与我试图使用的特定XLSX文件有关。我在Excel中创建了一个新的XLSX文件,并将其添加到我的项目中,结果成功了!然后,我只是将我需要的数据从给我错误的文件中粘贴到新创建的XLSX文件中,并对其进行解析!
static func load() {
guard let filePath = Bundle.main.path(forResource: "test", ofType: "xlsx", inDirectory: nil) else {
fatalError("XLSX file not exist")
}
let file = XLSXFile(filepath: filePath)
do {
let parseBooks = try? file?.parseWorkbooks()
for eachBook in parseBooks! {
for (name, path) in try file!.parseWorksheetPathsAndNames(workbook: eachBook) {
let worksheet = try file!.parseWorksheet(at: path)
let sharedStrings = try file!.parseSharedStrings()
print(sharedStrings)
}
}
} catch {
print("Error: (error.localizedDescription)")
}
}