在Swift中解析json blob字段

时间:2018-10-06 12:13:23

标签: json swift blob

我正在从Web服务中以以下格式快速读取JSON

[{
   "id":1,
   "shopName":"test",
   "shopBranch":"main",
   "shopAddress":"usa",
   "shopNumber":"5555555",
   "logo":[-1,-40,-1,-32],
   "shopPath":"test"
},
{
   "id":2,
   "shopName":"test",
   "shopBranch":"main",
   "shopAddress":"usa",
   "shopNumber":"66666666",
   "logo":[-1,-50,-2,-2],
   "shopPath":"test"
}]

我已经设法轻松地读取了所有字符串,但是当涉及徽标部分时,我不确定该怎么办,这是mySQL数据库中的blob字段,表示要在其中检索的图像。快速的用户界面,这是我执行此操作的代码,但我不断遇到错误,无法找到正确的方法:

struct Brand: Decodable {
    private enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "shopName"
        case branch = "shopBranch"
        case address = "shopAddress"
        case phone = "shopNumber"
        case logo = "logo"
        case path = "shopPath"
    }
    let id: Int
    let name: String
    let branch: String
    let address: String
    let phone: String
    let logo: [String]
    let path: String
}
func getBrandsJson() {
    let url = URL(string: "http://10.211.55.4:8080/exam/Test")
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else {
            print(error!);
            return
        }
        print(response.debugDescription)
        let decoder = JSONDecoder()
        let classes = try! decoder.decode([Brand].self, from: data)
        for myClasses in classes {
            print(myClasses.branch)
            if let imageData:Data = myClasses.logo.data(using:String.Encoding.utf8){
                let image = UIImage(data:imageData,scale:1.0)
                var imageView  : UIImageView!
            }
        }
    }).resume()
}

有人能解释一下如何正确地搜索我但是没有运气的方法

2 个答案:

答案 0 :(得分:0)

替换

let logo: [String]

使用

let logo: [Int]

使用错误获取

do {
     let classes = try JSONDecoder().decode([Brand].self, from: data)
}
catch {
  print(error)
}

答案 1 :(得分:0)

首先,您最好告诉Web服务的服务器端工程师,使用数字数组在JSON中返回二进制数据效率不高,他们应该使用Base-64或类似的东西。


如果他们固执地忽视了您的建议,则最好在自定义解码初始化程序中将其解码为Data

struct Brand: Decodable {
    private enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "shopName"
        case branch = "shopBranch"
        case address = "shopAddress"
        case phone = "shopNumber"
        case logo = "logo"
        case path = "shopPath"
    }
    let id: Int
    let name: String
    let branch: String
    let address: String
    let phone: String
    let logo: Data
    let path: String

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: CodingKeys.id)
        self.name = try container.decode(String.self, forKey: CodingKeys.name)
        self.branch = try container.decode(String.self, forKey: CodingKeys.branch)
        self.address = try container.decode(String.self, forKey: CodingKeys.address)
        self.phone = try container.decode(String.self, forKey: CodingKeys.phone)
        self.path = try container.decode(String.self, forKey: CodingKeys.path)
        //Decode the JSON array of numbers as `[Int8]`
        let bytes = try container.decode([Int8].self, forKey: CodingKeys.logo)
        //Convert the result into `Data`
        self.logo = Data(bytes: bytes.lazy.map{UInt8(bitPattern: $0)})
    }
}

您可以将getBrandsJson()的数据解码部分写为:

        let decoder = JSONDecoder()
        do {
            //You should never use `try!` when working with data returned by server
            //Generally, you should not ignore errors or invalid inputs silently
            let brands = try decoder.decode([Brand].self, from: data)
            for brand in brands {
                print(brand)
                //Use brand.logo, which is a `Data`
                if let image = UIImage(data: brand.logo, scale: 1.0) {
                    print(image)
                    //...
                } else {
                    print("invalid binary data as an image")
                }
            }
        } catch {
            print(error)
        }

我写了几行,用猜测将数字数组解码为Data。因此,如果您发现我的代码不适用于您实际的data,请告诉我足够的描述和一些实际数据示例。 (至少,您需要向我展示实际的"logo"数组中的前几百个元素。)