我的数据从未用可编码协议填充我的 class

My data never fill my class with codable protocol

我正在从格式类似于 JSON 的字符串中设置一个新的 class。 例如,当我尝试在 news.msg 内的可编码协议工作后查找数据时,我一无所获。

let jsonNews = """
[
{
"idPlace": "HexaId",
"namePlace": "A random name",
"dateMsg": "Timestamp",
"msg": "Message to display",
"urlPicture": "Url of the pic"
},
{
 "idPlace": "HexaId 2",
 "namePlace": "A random name 2",
 "dateMsg": "Timestamp 2",
 "msg": "Message to display 2",
 "urlPicture": "Url of the pic"
}
]
"""    

func getNews(){
var arrayNews: [News] = [News]()

if let dataFromString = jsonNews.data(using: .utf8, allowLossyConversion: false) {
    let json = try! JSON(data: dataFromString)
    for elem in json{
        debugPrint(elem.1)
        guard let data = try? elem.1.rawData() else {
            debugPrint("An error has occurred")
            return
        }
        guard let news = try? JSONDecoder().decode(News.self, from: data) else{
            debugPrint("An error has occurred")
            return

        }
        debugPrint(news.msg)
        arrayNews.append(news)
    }
}


import Foundation
import UIKit

class News: NSObject, Codable {
    let idPlace: String = ""
    let namePlace: String = ""
    let dateMsg: String = ""
    let msg: String = ""
    let urlPicture: String = ""
}

当我尝试显示新闻 news.msg 或任何其他 属性 时 class 是空的

因为你的 json 只是一个对象数组,所以不需要 foreach 循环,你可以通过将结果类型指定为解码结果应该是 News 数组方括号:[News].self

guard let news = try? JSONDecoder().decode([News].self, from: Data(jsonNews.utf8)) else {
    debugPrint("An error has occurred")
    return
}

debugPrint(news)
arrayNews = news

此外,如果没有特定原因说明您的模型应该继承 NSObject,您可以通过 struct 使模型更简单。您也不需要默认值,因为所有值都将由解码器初始化程序分配

struct News: Decodable {
    let idPlace, namePlace, dateMsg, msg, urlPicture: String
}