Swift 4,由于格式不正确,无法读取数据

时间:2018-07-17 16:29:01

标签: ios json swift parsing

我是SWIFT的新手。我开发项目以学习如何解析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"
    }
]
}

3 个答案:

答案 0 :(得分:2)

尝试一下

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

遍历您的数据

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

答案 1 :(得分:2)

? 实拍coding/decoding 错误

使用 codable 时,不要打印 .localizedDescription,而是尝试打印出 error 本身!所以编译器会准确描述问题所在!

do {
    let decoder = JSONDecoder()
    let decoded = try decoder.decode([Root].self, from: data!)
} catch {
    // print(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!)

答案 2 :(得分:-1)

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