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 {
18 return node(withArray: json)
20 if json.type == .dictionary {
22 return node(withDictionary: json)
25 return node(withObject: json)
28 private class func node(withObject obj: JSON) -> JSONNode? {
30 let node = JSONLeafNode()
35 case .string: value = obj.stringValue
37 case .number: value = String(obj.intValue)
39 case .null: value = nil
54 private class func node(withArray array: JSON) -> JSONNode {
56 let node = JSONContainerNode()
57 node.children = array.compactMap { _, json in JSONNode.nodeWithJSON(json) }
62 private class func node(withDictionary dict: JSON) -> JSONNode {
64 let node = JSONContainerNode()
65 node.children = dict.compactMap { (key: String, json: JSON) -> JSONNode? in
67 if let node = JSONNode.nodeWithJSON(json) {
80 @objc var key: String?
81 @objc var value: String?
83 @objc var children: [JSONNode] = []
84 @objc var isLeaf: Bool { return false }
86 // MARK: - NSCoding, NSCopying
87 required convenience init?(coder aDecoder: NSCoder) {
92 func encode(with aCoder: NSCoder) {
94 fatalError("Subclass MUST implement this method")
97 func copy(with zone: NSZone? = nil) -> Any {
99 fatalError("Subclass MUST implement this method")
103 final class JSONContainerNode: JSONNode {
110 override var value: String? {
112 get { return "\(children.count) items" }
116 override func copy(with zone: NSZone?) -> Any {
118 let node = JSONContainerNode()
119 node.children = children
124 required convenience init?(coder aDecoder: NSCoder) {
128 self.children = aDecoder.decodeObject(forKey: "children") as? [JSONNode] ?? []
131 override func encode(with aCoder: NSCoder) {
133 aCoder.encode(children, forKey: "children")
137 final class JSONLeafNode: JSONNode {
144 override var isLeaf: Bool { return true }
146 override func copy(with zone: NSZone?) -> Any {
148 let node = JSONLeafNode()
155 required convenience init?(coder aDecoder: NSCoder) {
159 self.value = aDecoder.decodeObject(forKey: "value") as? String
160 self.key = aDecoder.decodeObject(forKey: "key") as? String
163 override func encode(with aCoder: NSCoder) {
165 aCoder.encode(value, forKey: "value")
166 aCoder.encode(key, forKey: "key")