5 // Created by Hori,Masaki on 2017/01/05.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 class JSONNode: NSObject, NSCoding, NSCopying {
14 class func nodeWithJSON(_ json: JSON) -> JSONNode? {
16 if json.type == .array { return node(withArray: json) }
17 if json.type == .dictionary { return node(withDictionary: json) }
19 return node(withObject: json)
22 private class func node(withObject obj: JSON) -> JSONNode? {
24 let node = JSONLeafNode()
28 case .string: value = obj.stringValue
29 case .number: value = String(obj.intValue)
30 case .null: value = nil
31 default: print(obj); return nil
39 private class func node(withArray array: JSON) -> JSONNode {
41 let node = JSONContainerNode()
42 node.children = array.flatMap { _, json in JSONNode.nodeWithJSON(json) }
47 private class func node(withDictionary dict: JSON) -> JSONNode {
49 let node = JSONContainerNode()
50 node.children = dict.flatMap { (key: String, json: JSON) -> JSONNode? in
52 if let node = JSONNode.nodeWithJSON(json) {
65 @objc var key: String?
66 @objc var value: String?
68 @objc var children: [JSONNode] = []
69 @objc var isLeaf: Bool { return false }
71 // MARK: - NSCoding, NSCopying
72 required convenience init?(coder aDecoder: NSCoder) {
77 func encode(with aCoder: NSCoder) {
79 fatalError("Subclass MUST implement this method")
82 func copy(with zone: NSZone? = nil) -> Any {
84 fatalError("Subclass MUST implement this method")
88 final class JSONContainerNode: JSONNode {
95 override var value: String? {
97 get { return "\(children.count) items" }
101 override func copy(with zone: NSZone?) -> Any {
103 let node = JSONContainerNode()
104 node.children = children
109 required convenience init?(coder aDecoder: NSCoder) {
113 self.children = aDecoder.decodeObject(forKey: "children") as? [JSONNode] ?? []
116 override func encode(with aCoder: NSCoder) {
118 aCoder.encode(children, forKey: "children")
122 final class JSONLeafNode: JSONNode {
129 override var isLeaf: Bool { return true }
131 override func copy(with zone: NSZone?) -> Any {
133 let node = JSONLeafNode()
140 required convenience init?(coder aDecoder: NSCoder) {
144 self.value = aDecoder.decodeObject(forKey: "value") as? String
145 self.key = aDecoder.decodeObject(forKey: "key") as? String
148 override func encode(with aCoder: NSCoder) {
150 aCoder.encode(value, forKey: "value")
151 aCoder.encode(key, forKey: "key")