I know that there are libraries that do this, I think that is a way much easier to accomplish (in terms of implementation).
i.e. ObjectMapper
With this lib you need to set a method map and then the properties that would be mapped I want to accomplish this without setting the method map, just do the same way that would be with C#
i.e. WSD.Data
What I mean? just want to do this way
public class User : Mapper
{
username: String
email: String
picture: File // a custom class
}
var jsonString: String = "{\"username\": \"myUsername\", \"email\": \"my@email.com\", \"picture\": {\"url\": \"http://ift.tt/1B9TKWn\"}}"
User().set(jsonString)
can be or not exactly this way, but just set the object with properties and then with a method map the json to the object, maybe we can pass the json string in the constructor.
I'm just experimenting with this
public class Mappable : NSObject { func Map () -> [String: String] { return String: String }
public func Set (JSONString: String)
{
// Now get the mapped fields
var mapped: [String: String] = Map()
println(NSStringFromClass(self.dynamicType).componentsSeparatedByString("."))
var error : NSError?
let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData!, options: nil, error: &error) as NSDictionary
for (key, value) in JSONDictionary {
var keyName = key as String
if self.respondsToSelector(NSSelectorFromString(mapped[keyName])) {
keyName = mapped[keyName]!
}
// If property exists
if self.respondsToSelector(NSSelectorFromString(keyName)) {
if (self[keyName] is Mappable) { // Here don't know how to check the property type, so I can cast
var err: NSError?
(self[keyName] as Mappable).Set(NSJSONSerialization.dataWithJSONObject(value, options:NSJSONWritingOptions(0), error: &err))
} else {
println("property: " + keyName)
self.setValue(value, forKey: keyName)
}
} else {
println("no property " + keyName)
}
}
}
}
This prototype also lack recursion..
Aucun commentaire:
Enregistrer un commentaire