如何使用多级节点创建用于将JSON反序列化的结构

时间:2016-10-17 07:36:08

标签: swift

让我说我有这个JSON例如

{
    "kind": "Listing",
    "data": {
        "children": {
            "domain": "twitlonger.com",
            "other": "blahblah"
        },
        "children": {
            "domain": "Otherplace.com",
            "other": "blahblah"
        }
    }
}

我如何创建一个结构来将其反序列化为例如。

-Puedo code -

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]) {

    }
}

1 个答案:

答案 0 :(得分:0)

对于给定的JSON,声明两个结构ChildJSONResp

如果缺少kinddatachildren的其中一个值,则初始化将失败

struct Child {
  let domain : String
  let other : String
}

struct JSONResp {
  let kind : String
  var children = [Child]()

  init?(json: [String: Any]) {
    guard let kind = json["kind"] as? String,
      let data = json["data"] as? [String:Any],
      let kids = data["children"] as? [[String:Any]] else {
        return nil
    }
    self.kind = kind
    for child in kids {
      if let domain = child["domain"] as? String,
        let other = child["other"] as? String {
        children.append(Child(domain: domain, other: other))
      }
    }
  }
}