簡體   English   中英

Swift - 無法讀取數據,因為它的格式不正確

[英]Swift - The data couldn’t be read because it isn’t in the correct format

我正在開發一個項目來學習如何解析 JSON。 我正在嘗試將JSON解析為struct 我正在嘗試使用接下來的代碼來執行此操作,但出現以下錯誤:

Err 無法讀取數據,因為它的格式不正確。

我究竟做錯了什么? 我也嘗試使用 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"
    }
]
}

💡 排查coding / decoding錯誤

使用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!)

嘗試這個

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)")
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM