Swift JSON转换为模型类

时间:2018-07-13 06:32:32

标签: json swift parsing

我想将JSON中的所有数据放入模型类。我该怎么做?我将在下面填写所有字段和我的代码!

模型

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"
}

1 个答案:

答案 0 :(得分:1)

  

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

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

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

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

} catch {
    // print error here.  
}

我希望这对您有帮助。