我上课
class Event{
var name:String = "";
var attributes:[String:Any] = [:];
var lineItems:[LineItem] = [];
}
class LineItem {
var itemName:String = "";
var details:[String:Any] = [:];
}
我想将其转换为json字符串,然后将json字符串转换回模型。
我尝试
var test = Event()
test.name = "jogi"
var dictionary = Dictionary<String,Any>();
dictionary.updateValue("shoes", forKey: "item")
dictionary.updateValue(345, forKey: "amount")
test.attributes = dictionary
let json = JSON(test)
但是它会给出类型不受支持的错误,因为swiftyjson仅支持rawArray
,rawDictionary
,rawString
,rawNumber
,rawNull
,rawBool
答案 0 :(得分:2)
您可以使您的课程符合Codable
协议
class Event: Codable {
var name:String = "";
var attributes:[String:Any] = [:];
var lineItems:[LineItem] = [];
}
然后使用以下代码对模型进行编码:
try? JSONEncoder().encode(event)
要解码模型,请使用
try? JSONDecoder().decode(Event.self, from: eventData)