How to implement json string mapper swift object?
class User{
var name:String
var age:Int
}
Easy way to convert User object to a json string? and convert a json string to User object?
Check out SwiftyJSON doc's about initialization https://github.com/SwiftyJSON/SwiftyJSON#initialization
Basically your only option is to write a method to convert your object into a dictionary and other one that can build your object from dictionary.
Simple example for your two properties User:
class User {
var name:String
var age:Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
extension User {
convenience init(userDict: [String : AnyObject]) {
let name = userDict["name"] as! String
let age = userDict["age"] as! Int
self.init(name: name, age: age)
}
func serialize() -> [String : AnyObject] {
return ["name": name, "age": age]
}
}
Then if you want to pass json strings around your app you can check out
NSJSONSerialization.dataWithJSONObject
NSString(data: yourdata, encoding: NSUTF8StringEncoding)
to produce a json string. There is also NSJSONSerialization.JSONObjectWithData
to convert your data the other way around.
Hope that helps!
Edit: To return a string containing JSON replace serialize method with following:
func serialize() -> String? {
if let data = try? NSJSONSerialization.dataWithJSONObject(["name": name, "age": age], options: NSJSONWritingOptions(rawValue: 0)) {
if let s = NSString(data: data, encoding: NSUTF8StringEncoding) {
return s as String
}
}
return nil
}
I used to make a SwiftyJSON JSON object by setting the key and value for each variable, but it felt tedious doing it for every class I make and wasn't flexible when you add new variables to it, so I found a better way for Swift 2.0.
With Swift 2.0, they introduced a class called Mirror. By using this, you can iterate through your lets and variables as such:
class User {
var name:String
var age:Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
var json: JSON {
get {
var dict = [String: AnyObject]()
let mirror = Mirror(reflecting: self)
for (_, attr) in mirror.children.enumerate() {
if let property_name = attr.label as String! {
dict[property_name] = attr.value as? AnyObject
}
}
return JSON(dict)
}
}
}
So, if you want to get a JSON version of your declared variables and values:
let user1 = User(name: "Bob", age: 52)
print(user1.json)
This will get you:
{
"age" : 52,
"name" : "Bob"
}
For getting the String, look at this answer:
user1.json.rawString()!