Swift 4无法读取数据,因为格式不正确 [英] Swift 4 The data couldn’t be read because it isn’t in the correct format

查看:167
本文介绍了Swift 4无法读取数据,因为格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是SWIFT的新手。我开发项目来学习如何解析JSON。我正在尝试将 JSON 解析为 struct 。我试着这样做。所以我得到的错误就像
错误数据无法读取,因为格式不正确。
我做错了什么?此外,我试图使用Alamofire但我没有找到解析它的方法。

I am new in SWIFT. I develop project to learn how to parse JSON. I am trying to parse JSON to struct. I try to do this way. So i get error like Err The data couldn’t be read because it isn’t in the correct format. What i do wrong? Also i tried to use Alamofire but i didn't find way to parse it to 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

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


推荐答案

试试这个

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

遍历您的数据

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

这篇关于Swift 4无法读取数据,因为格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆