可以說我有這個JSON例如如何創建一個struct反序列化JSON進,與多級節點
{
"kind": "Listing",
"data": {
"children": {
"domain": "twitlonger.com",
"other": "blahblah"
},
"children": {
"domain": "Otherplace.com",
"other": "blahblah"
}
}
}
我怎麼能創建一個結構來反序列化爲例如這個
-Psuedo代碼 -
struct JSONResp {
let kind:String
let data:[String: Any] {
let children:[String: Any] {
let domain:String
let other:String
}
}
}
extension JSONResp {
init?(json: [String: Any]) {
// Deserialize my stuff
}
}
我從Golang未來,我只想能夠做到
type JSONResp struct {
Kind string
Data []children
}
type children struct {
Domain string
Other string
}
的任何信息將是巨大的感謝在哪裏。
這裏有點兒我到目前爲止所做的事情,我不知道它是否正確,只是做了一些我通過Go教會我的直覺。
import Foundation
struct Subreddit {
let kind:String
let data:[Data]
}
struct Data {
let modhash:String
let children:[Children]
}
struct Children {
let kind:String
let data:[Payload]
}
struct Payload {
let contest_mode:Bool
let banned_by:NSNull
let domain:String
let subreddit:String
let selftext_html:String
let selftext:String
let likes:NSNull
let suggested_sort:NSNull
let saved:Bool
let id:String
let gilded:Int
let clicked:Bool
let author:String
let name:String
let score:Int
let over_18:Bool
let hidden:Bool
let thumbnail:String
let subreddit_id:String
let link_flair_css_class:String
let author_flair_css_class:String
let permalink:String
let Preview:[Preview]
let locked:Bool
let stickied:Bool
let created:Float64
let url:String
let author_flair_text:String
let quarantine:Bool
let title:String
let created_utc:Float64
let link_flair_text:String
let num_comments:UInt32
let visited:Bool
let ups:UInt32
}
struct Preview {
let images:[Images]
}
struct Images {
let source:[String:Any]
let resolutions:[String:Any]
let id:String
}
extension Subreddit {
init?(json: [String: Any]) {
}
}
[SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)建議 –
誠然它不」初始化將失敗對這個問題有幫助,但我認爲這可能有助於作者*。我廣泛使用它。它既不慢也不麻煩... –