How do I unmarshal JSON onto a swift class? Here is Go code which illustrates what I am after.
I can't find any reference which shows how to do this in Swift. A reference I looked at ( among others ) was this tutorial.
But those example uses dictionaries. I want to use objects.
I saw attempts around this la: http://bit.ly/1t3W2Gi
but that post does not unmarshal to a class.
We've written an open source, protocol-based Swift framework called ObjectMapper that you might want to consider. From the README:
To support mapping, a class just needs to implement the MapperProtocol. ObjectMapper uses the "<=" operator to define how each member variable maps to and from JSON.
class User: MapperProtocol {
var username: String?
var age: Int?
var weight: Double?
var arr: [AnyObject]?
var dict: [String : AnyObject] = [:]
var friend: User?
var birthday: NSDate?
// MapperProtocol
class func map(mapper: Mapper, object: User) {
object.username <= mapper["username"]
object.age <= mapper["age"]
object.weight <= mapper["weight"]
object.arr <= mapper["arr"]
object.dict <= mapper["dict"]
object.friend <= mapper["friend"]
object.birthday <= (mapper["birthday"], DateTransform<NSDate, Int>())
}
}
While not as unobtrusive as, say, Gson for Java, it's fairly lightweight and explicit. Although it's in beta, we're happily using it internally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With