Swift-通过JSON响应创建数据模型 [英] Swift - Create data model from JSON response

查看:124
本文介绍了Swift-通过JSON响应创建数据模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Swift lang,而听到其他人提供的有关您如何处理JSON响应中的模型"的信息将是一件很棒的事情?例如-

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 -

我有User.swift模型:

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

,我也想像在Obj-C项目中一样使用 KeyValueObjectMapping .不幸的是,这在这里不起作用:

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

如何在Swift中创建模型?

How do you create your models in Swift?

推荐答案

我建议使用代码生成在Swift中基于JSON生成模型.为此,我在 http://www.guideluxe.com/JsonToSwift 处创建了一个工具,以进行JSON建模和解析尽可能简单.

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.

向工具提交带有类名的示例JSON对象后,它将生成一个相应的Swift类以及所有需要的辅助Swift类,以表示示例JSON所隐含的结构.还包括用于填充Swift对象的类方法,其中包括一种利用NSJSONSerialization.JSONObjectWithData方法的方法.提供了NSArray和NSDictionary对象的必要映射.

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.

将生成的代码作为Swift类复制到项目中之后,只需提供一个包含与提供给该工具的示例匹配的JSON的NSData对象.

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.

除Foundation之外,没有依赖项.

Other than Foundation, there are no dependencies.

这是从JSON文件创建NSData对象进行测试的方法.

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)!

这篇关于Swift-通过JSON响应创建数据模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆