如何将图片从JSON解析到swift4

brvekthn  于 2023-08-08  发布在  Swift
关注(0)|答案(1)|浏览(100)

我正在尝试从我的数据库中提取图像在swift。我可以检索价格、视频和p_name,但不能检索图像。我想用数据库中的图像更新updateImage UIImageView,但我得到两个错误。
Error one说道:
类型“ViewController.Class”不符合协议“Encodable”
Error two说:
类型“ViewController.Class”不符合协议“Dec
对此有哪些好的变通方法?
下面是JSON:

{
"id":"1",
"p_name":"item_one",
"image":"item_one.png"
}
{
"id":"2","p_name":
"item_two","image":
"item_two.img"
}

字符串
Swift代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var updateLabel: UILabel!

@IBOutlet weak var updateImage: UILabel!

struct Class: Codable
{
    let id: String
    let p_name: String
    let image: String

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let url = URL(string: "http://host-2:8888//getClasses.php")

    // Load the URL
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        // If there are any errors don't try to parse it, show the error
        guard let data = data, error == nil else { print(error!); return }

        let decoder = JSONDecoder()
        let classes = try! decoder.decode([Class].self, from: data)
        // Print out the classes to the console - try sticking this in a table view :)
        for myClass in classes {

            self.updateLabel.text = myClass.p_name
            self.updateImage.text = myClass.image

        }

    }).resume()

    }
}

rslzwgfq

rslzwgfq1#

首先,如果从API中获取的键与Codable Type中的属性名称相同,则不需要显式指定enum CodingKeys,即您可以简单地用途:

struct Class: Codable
{
    let id: String
    let p_name: String
    let image: String
}

字符串
据我所知,你必须用以下方式解码你得到的JSON data

let jsonString = """
    [
        {"id": "1", "p_name": "P1", "image": "V1"},
        {"id": "2", "p_name": "P2", "image": "V2"},
        {"id": "3", "p_name": "P3", "image": "V3"}
    ]
    """
    if let jsonData = jsonString.data(using: .utf8)
    {
        let obj = try? JSONDecoder().decode([Class].self, from: jsonData)
        print(obj)
    }


在上面的代码中,我刚刚使用了一个示例JSON string。要了解更多信息,您必须添加从API获得的确切JSON响应。
现在,如果您还希望从API获得一个图像URL,那么您还没有添加任何属性来将该URL字符串存储在struct Class中。

相关问题