5 // Created by Hori,Masaki on 2017/01/05.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 class JSONNode: NSObject, NSCoding, NSCopying {
13 class func nodeWithJSON(_ json: JSON) -> JSONNode? {
14 if json.type == .array { return node(withArray: json) }
15 if json.type == .dictionary { return node(withDictionary: json) }
16 return node(withObject: json)
18 private class func node(withObject obj: JSON) -> JSONNode? {
19 let node = JSONLeafNode()
22 case .string: value = obj.stringValue
23 case .number: value = String(obj.intValue)
24 case .null: value = nil
25 default: print(obj); return nil
30 private class func node(withArray array: JSON) -> JSONNode {
31 let node = JSONContainerNode()
32 node.children = array.flatMap { (_, json) in JSONNode.nodeWithJSON(json) }
35 private class func node(withDictionary dict: JSON) -> JSONNode {
36 let node = JSONContainerNode()
37 node.children = dict.flatMap { (key: String, json: JSON) -> JSONNode? in
38 if let node = JSONNode.nodeWithJSON(json) {
50 var children: [JSONNode] = []
51 var isLeaf: Bool { return false }
53 // MARK: - NSCoding, NSCopying
54 required convenience init?(coder aDecoder: NSCoder) {
57 func encode(with aCoder: NSCoder) {
58 fatalError("Subclass MUST implement this method")
60 func copy(with zone: NSZone? = nil) -> Any {
61 fatalError("Subclass MUST implement this method")
65 class JSONContainerNode: JSONNode {
70 override var value: String? {
72 return "\(children.count) items"
77 override func copy(with zone: NSZone?) -> Any {
78 let node = JSONContainerNode()
79 node.children = children
82 required convenience init?(coder aDecoder: NSCoder) {
84 self.children = aDecoder.decodeObject(forKey: "children") as? [JSONNode] ?? []
86 override func encode(with aCoder: NSCoder) {
87 aCoder.encode(children, forKey: "children")
91 class JSONLeafNode: JSONNode {
96 override var isLeaf: Bool { return true }
98 override func copy(with zone: NSZone?) -> Any {
99 let node = JSONLeafNode()
104 required convenience init?(coder aDecoder: NSCoder) {
106 self.value = aDecoder.decodeObject(forKey: "value") as? String
107 self.key = aDecoder.decodeObject(forKey: "key") as? String
109 override func encode(with aCoder: NSCoder) {
110 aCoder.encode(value, forKey: "value")
111 aCoder.encode(key, forKey: "key")