Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I unmarshal JSON to a class in swift?

Tags:

json

swift

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.

like image 430
rexposadas Avatar asked Feb 11 '23 18:02

rexposadas


1 Answers

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.

like image 95
Nathan Smith Avatar answered Feb 14 '23 09:02

Nathan Smith