Bruno Bu
Bruno Bu

Reputation: 63

How to deserialize JSON to a Swift object?

Is there any way to deserialize JSON to a Swift object, not to NSDictionay?

For example: a JSON is like: {"value": "xxx"}

I want to use this resource like:

var json = "{\"value\": \"xxx\"}"
var obj = parseToObj(json)
println(obj.value)

Upvotes: 1

Views: 1269

Answers (1)

isair
isair

Reputation: 1860

I wrote a small library to handle things like this swiftly. (No pun intended) You can get it here: JSONHelper

After reading your question I realized that I should add deserialization support directly from JSON strings and not just JSON response objects, so I did.

Here is how you do it:

struct MyObjectType: Deserializable {
    var value: String?

    init(data: [String: AnyObject]) {
        value <-- data["value"]
    }
}

var json = "{\"value\": \"xxx\"}"
var myClass: MyClass?

myClass <-- json

println("\(myClass.value)")

Upvotes: 2

Related Questions