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

w7t8yxp5  于 12个月前  发布在  Swift
关注(0)|答案(3)|浏览(142)

我正在开发一个项目来学习如何解析JSON。我试图将JSON解析为struct。我试图使用接下来的代码来完成它,但我得到了以下错误:
无法读取数据,因为它的格式不正确。
我做错了什么?我也尝试使用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

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/[email protected]"
    },
    {
        "id": 2,
        "name": "Кафе",
        "image": "http://95.46.99.250:9095/storage/photos/[email protected]"
    },
    {
        "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/[email protected]"
    },
    {
        "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 [email protected]"
    }
]
}

roejwanj

roejwanj1#

排除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!)

htzpubme

htzpubme2#

试试这个

let gitData = try decoder.decode(Root.self, from: data!)

字符串
遍历数据

for singleData in gitData.data where (singleData.name ?? "") == "Cafe" {
    print(singleData.image)
}

oug3syen

oug3syen3#

对我来说,“数据无法读取,因为它不是在正确的格式。”的问题是与特定的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)")
    }
  }

字符串

相关问题