I have a class
class Event{
var name:String = "";
var attributes:[String:Any] = [:];
var lineItems:[LineItem] = [];
}
class LineItem {
var itemName:String = "";
var details:[String:Any] = [:];
}
I want to convert it into json string and json string back to model.
I try
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)
But it give an error of unsupported Type because swiftyjson support only rawArray
, rawDictionary
, rawString
, rawNumber
, rawNull
, rawBool
.
You could make your Class conform to Codable
protocol
class Event: Codable {
var name:String = "";
var attributes:[String:Any] = [:];
var lineItems:[LineItem] = [];
}
Then to encode your model use:
try? JSONEncoder().encode(event)
To decode your model use
try? JSONDecoder().decode(Event.self, from: eventData)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.