5 // Created by Hori,Masaki on 2014/02/11.
6 // Copyright (c) 2014年 Hori,Masaki. All rights reserved.
13 @interface HMJSONNode ()
14 @property (copy, readwrite) NSString *key;
15 @property (copy, readwrite) NSString *value;
20 @interface HMJSONContainerNode : HMJSONNode
21 @property (strong) NSArray *childrenArray;
24 @interface HMJSONLeafNode : HMJSONNode
29 @implementation HMJSONNode
31 + (id)nodeWithJSON:(id)json
34 if([json isKindOfClass:[NSArray class]]) {
35 NSMutableArray *array = [NSMutableArray new];
36 for(id element in json) {
37 HMJSONNode *node = [HMJSONNode nodeWithJSON:element];
38 if(![node isKindOfClass:[HMJSONNode class]]) {
39 node = [HMJSONLeafNode new];
42 [array addObject:node];
44 HMJSONContainerNode *node = [HMJSONContainerNode new];
45 node.childrenArray = array;
50 if([json isKindOfClass:[NSDictionary class]]) {
51 NSMutableArray *array = [NSMutableArray new];
54 HMJSONNode *node = [HMJSONNode nodeWithJSON:json[key]];
55 if([node isKindOfClass:[HMJSONNode class]]) {
58 node = [HMJSONLeafNode new];
60 node.value = json[key];
62 [array addObject:node];
64 HMJSONContainerNode *node = [HMJSONContainerNode new];
65 node.childrenArray = array;
72 - (id)copyWithZone:(NSZone *)zone
74 @throw [NSException exceptionWithName:@"Subclass MUST implement method."
75 reason:@"Subclass MUST implement method."
79 - (id)initWithCoder:(NSCoder *)aDecoder
81 @throw [NSException exceptionWithName:@"Subclass MUST implement method."
82 reason:@"Subclass MUST implement method."
86 - (void)encodeWithCoder:(NSCoder *)aCoder
88 @throw [NSException exceptionWithName:@"Subclass MUST implement method."
89 reason:@"Subclass MUST implement method."
96 @implementation HMJSONContainerNode
98 - (id)copyWithZone:(NSZone *)zone
100 HMJSONContainerNode *res = [[self class] new];
101 res.value = self.value;
102 res.childrenArray = self.childrenArray;
107 - (id)initWithCoder:(NSCoder *)aDecoder
109 HMJSONContainerNode *node = [HMJSONContainerNode new];
110 node.childrenArray = [aDecoder decodeObjectForKey:@"children"];
111 node.key = [aDecoder decodeObjectForKey:@"key"];
115 - (void)encodeWithCoder:(NSCoder *)aCoder
117 [aCoder encodeObject:self.children forKey:@"children"];
118 [aCoder encodeObject:self.key forKey:@"key"];
124 return [NSString stringWithFormat:@"%ld items", [self.children count]];
128 - (NSArray *)children
130 return self.childrenArray;
141 @implementation HMJSONLeafNode
142 - (id)copyWithZone:(NSZone *)zone
144 HMJSONLeafNode *res = [[self class] new];
146 res.value = self.value;
150 - (id)initWithCoder:(NSCoder *)aDecoder
152 HMJSONLeafNode *node = [HMJSONLeafNode new];
153 node.value = [aDecoder decodeObjectForKey:@"value"];
154 node.key = [aDecoder decodeObjectForKey:@"key"];
158 - (void)encodeWithCoder:(NSCoder *)aCoder
160 [aCoder encodeObject:self.value forKey:@"value"];
161 [aCoder encodeObject:self.key forKey:@"key"];
164 - (NSArray *)children