我正在从类似JSON格式的字符串中设置一个新类。 例如,当我尝试在news.msg内的可编码协议工作之后查找数据时,我什么都没找到。
[NotNull]
当我尝试显示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 = ""
}
或“新闻”类中的其他任何属性为空
答案 0 :(得分:2)
由于您的json只是对象数组,因此不需要foreach循环,您只需将结果类型放在方括号中即可指定解码结果应为News
数组:{{1 }}
[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