Kosmetika Kosmetika - 1 year ago 140
JSON Question

Swift - Create data model from JSON response

I'm learning Swift lang and one of the things that would be great to hear others input about is "How you handle models from JSON responses"? For example -

I have


class User: NSObject {
var user_token:String?
var email:String?

and also I would like to use KeyValueObjectMapping as I do in Obj-C projects. Unfortunately this doesn't work here:

let parser = DCKeyValueObjectMapping.mapperForClass(User)
let user = parser.parseDictionary(data.objectForKey("user") as NSDictionary) as User
println(user.user_token) // returns nil

How do you create your models in Swift?

Answer Source

I recommend using code generation to generate models in Swift based on JSON. To that end, I've created a tool at http://www.guideluxe.com/JsonToSwift to make modeling and parsing JSON as easy as possible.

After you've submited a sample JSON object with a class name to the tool, it will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.

After copying the generated code into your project as a Swift class(es), you only need to supply an NSData object containing JSON that matches the sample provided to the tool.

Other than Foundation, there are no dependencies.

Here's how to create an NSData object from a JSON file to test with.

let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!