我使用以下符合 Codable 的結構來表示我在 Set 中的資料,然后我將此 set 編碼為 JSON Array,如下所示 [{"myexample":"Example5","id":3}]
結構和編碼:
struct Model : Codable, Hashable {
var myexample: String?
var id: Int?
}
var mySet: Set<Model> = []
mySet.insert(Model(myexample: "Example4", id: 3))
do {
let json = try JSONEncoder().encode(mySet)
print(String(data: json, encoding: .utf8)!)
} catch {
print(error)
}
如何使用以下函式對該陣列進行反向解碼?
目前收到此錯誤:
“Set”型別的值沒有成員“utf8”
func processArray(array:Set<Model> = []) {
do{
let mydata = Data(array.utf8.data)
let decoded = try JSONDecoder().decode([Model].self,from: mydata)
print(decoded)
}catch let jsonErr {
print(jsonErr)
}
}
uj5u.com熱心網友回復:
JSON 是字串格式,因此JSON 陣列也是字串
func processJSON(_ json: String) {
do{
let mydata = Data(json.utf8)
let decoded = try JSONDecoder().decode(Set<Model>.self,from: mydata)
print(decoded)
} catch {
print(error)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410735.html
標籤:
下一篇:帶狀矩形
