Swift JSON 到模型类 [英] Swift JSON to Model Class

查看:47
本文介绍了Swift JSON 到模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有数据从我的 JSON 放到模型类中.我怎么能这样做?所有字段和我的代码我都会放在下面!

I want to put all data from my JSON to model class. How i can do that? All fields and my code i will put right below!

模型

class FacebookUser: NSObject {
    var first_name: String?
    var id: String?
    var last_name: String?
    var name: String?
    var picture: String?

    init(dictionary: [String: AnyObject]) {
        self.first_name = dictionary["first_name"] as? String
        self.id = dictionary["id"] as? String
        self.last_name = dictionary["last_name"] as? String
        self.name = dictionary["name"] as? String
        self.picture = dictionary["picture"] as? String
    }
}

JSON 示例

{
    "picture" : {
        "data" : {
            "height" : 50,
            "is_silhouette" : false,
            "url" : "link",
            "width" : 50
        }
    },
    "name" : "George Heinz",
    "last_name" : "Heinz",
    "id" : "1860499320637949",
    "first_name" : "George"
}

推荐答案

我假设您有 Data 格式的 json 和所有字段 Optional

I assume that you have json in Data format and All field Optional

创建以下可解码的 json 模型类,用于解码您的 json 数据.

Create following decodable json model class which are used to decode your json data.

struct PictureJson: Decodable {
    var picture         : Data?
    var name            : String?
    var last_name       : String?
    var id              : String?
    var first_name      : String?
}

struct Data: Decodable {
    var data            : ImageData?
}

struct ImageData : Decodable {
    var height          : Int?
    var is_silhouette   : Bool?
    var url             : String?
    var width           : Int?
}

并编写以下代码来解码您的json

And write following code to decode your json

do {
    let picture = try JSONDecoder().decode(PictureJson.self, from: jsonData!) as? PictureJson
     print(picture!.picture!.data)

} catch {
    // print error here.  
}

希望对你有帮助.

这篇关于Swift JSON 到模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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