Swift JSON到模型类



我想把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"
}

我假设您有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.  
}

我将建议创建模型的url。

  1. http://www.jsoncafe.com

  2. https://app.quicktype.io

您可以将json放在这里,然后进行转换。

最新更新