forked from scrod/nv
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNSScanner+BSJSONAdditions.m
executable file
·325 lines (288 loc) · 11.6 KB
/
NSScanner+BSJSONAdditions.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//
// BSJSONAdditions
//
// Created by Blake Seely on 2/1/06.
// Copyright 2006 Blake Seely - http://www.blakeseely.com All rights reserved.
// Permission to use this code:
//
// Feel free to use this code in your software, either as-is or
// in a modified form. Either way, please include a credit in
// your software's "About" box or similar, mentioning at least
// my name (Blake Seely).
//
// Permission to redistribute this code:
//
// You can redistribute this code, as long as you keep these
// comments. You can also redistribute modified versions of the
// code, as long as you add comments to say that you've made
// modifications (keeping these original comments too).
//
// If you do use or redistribute this code, an email would be
// appreciated, just to let me know that people are finding my
// code useful. You can reach me at blakeseely@mac.com
//
//
// Version 1.2: Includes modifications by Bill Garrison: http://www.standardorbit.com , which included
// Unit Tests adapted from Jonathan Wight's CocoaJSON code: http://www.toxicsoftware.com
// I have included those adapted unit tests in this package.
#import "NSScanner+BSJSONAdditions.h"
NSString *jsonObjectStartString = @"{";
NSString *jsonObjectEndString = @"}";
NSString *jsonArrayStartString = @"[";
NSString *jsonArrayEndString = @"]";
NSString *jsonKeyValueSeparatorString = @":";
NSString *jsonValueSeparatorString = @",";
NSString *jsonStringDelimiterString = @"\"";
NSString *jsonStringEscapedDoubleQuoteString = @"\\\"";
NSString *jsonStringEscapedSlashString = @"\\\\";
NSString *jsonTrueString = @"true";
NSString *jsonFalseString = @"false";
NSString *jsonNullString = @"null";
NSString *jsonIndentString = @"\t"; // Modify this string to change how the output formats.
const NSInteger jsonDoNotIndent = -1;
@implementation NSScanner (PrivateBSJSONAdditions)
- (BOOL)scanJSONObject:(NSDictionary **)dictionary
{
//[self setCharactersToBeSkipped:nil];
BOOL result = NO;
// Bypass irrelevant characters at the beginning of a JSON string
NSString *ignoredString;
[self scanUpToString:jsonObjectStartString intoString:&ignoredString];
if (![self scanJSONObjectStartString]) {
// TODO: Error condition. For now, return false result, do nothing with the dictionary handle
} else {
NSMutableDictionary *jsonKeyValues = [[[NSMutableDictionary alloc] init] autorelease];
NSString *key = nil;
id value;
[self scanJSONWhiteSpace];
while (([self scanJSONString:&key]) && ([self scanJSONKeyValueSeparator]) && ([self scanJSONValue:&value])) {
[jsonKeyValues setObject:value forKey:key];
[self scanJSONWhiteSpace];
// check to see if the character at scan location is a value separator. If it is, do nothing.
if ([[[self string] substringWithRange:NSMakeRange([self scanLocation], 1)] isEqualToString:jsonValueSeparatorString]) {
[self scanJSONValueSeparator];
}
}
if ([self scanJSONObjectEndString]) {
// whether or not we found a key-val pair, we found open and close brackets - completing an object
result = YES;
*dictionary = jsonKeyValues;
}
}
return result;
}
- (BOOL)scanJSONArray:(NSArray **)array
{
BOOL result = NO;
NSMutableArray *values = [[[NSMutableArray alloc] init] autorelease];
[self scanJSONArrayStartString];
id value = nil;
while ([self scanJSONValue:&value]) {
[values addObject:value];
[self scanJSONWhiteSpace];
if ([[[self string] substringWithRange:NSMakeRange([self scanLocation], 1)] isEqualToString:jsonValueSeparatorString]) {
[self scanJSONValueSeparator];
}
}
if ([self scanJSONArrayEndString]) {
result = YES;
*array = values;
}
return result;
}
- (BOOL)scanJSONString:(NSString **)string
{
BOOL result = NO;
if ([self scanJSONStringDelimiterString]) {
NSMutableString *chars = [[[NSMutableString alloc] init] autorelease];
// process character by character until we finish the string or reach another double-quote
while ((![self isAtEnd]) && ([[self string] characterAtIndex:[self scanLocation]] != '\"')) {
unichar currentChar = [[self string] characterAtIndex:[self scanLocation]];
unichar nextChar;
if (currentChar != '\\') {
[chars appendFormat:@"%C", currentChar];
[self setScanLocation:([self scanLocation] + 1)];
} else {
nextChar = [[self string] characterAtIndex:([self scanLocation] + 1)];
switch (nextChar) {
case '\"':
[chars appendString:@"\""];
break;
case '\\':
[chars appendString:@"\\"];
break;
case '/':
[chars appendString:@"/"];
break;
case 'b':
[chars appendString:@"\b"];
break;
case 'f':
[chars appendString:@"\f"];
break;
case 'n':
[chars appendString:@"\n"];
break;
case 'r':
[chars appendString:@"\r"];
break;
case 't':
[chars appendString:@"\t"];
break;
case 'u': // unicode sequence - get string of hex chars, convert to int, convert to unichar, append
[self setScanLocation:([self scanLocation] + 2)]; // advance past '\u'
if (![self scanUnicodeCharacterIntoString: chars]) return NO;
[self setScanLocation:([self scanLocation] + 2)];
break;
default:
[chars appendFormat:@"\\%C", nextChar];
break;
}
[self setScanLocation:([self scanLocation] + 2)];
}
}
if (![self isAtEnd]) {
result = [self scanJSONStringDelimiterString];
*string = chars;
}
return result;
/* this code is more appropriate if you have a separate method to unescape the found string
for example, between inputting json and outputting it, it may make more sense to have a category on NSString to perform
escaping and unescaping. Keeping this code and looking into this for a future update.
NSUInteger searchLength = [[self string] length] - [self scanLocation];
NSUInteger quoteLocation = [[self string] rangeOfString:jsonStringDelimiterString options:0 range:NSMakeRange([self scanLocation], searchLength)].location;
searchLength = [[self string] length] - quoteLocation;
while (([[[self string] substringWithRange:NSMakeRange((quoteLocation - 1), 2)] isEqualToString:jsonStringEscapedDoubleQuoteString]) &&
(quoteLocation != NSNotFound) &&
(![[[self string] substringWithRange:NSMakeRange((quoteLocation -2), 2)] isEqualToString:jsonStringEscapedSlashString])){
searchLength = [[self string] length] - (quoteLocation + 1);
quoteLocation = [[self string] rangeOfString:jsonStringDelimiterString options:0 range:NSMakeRange((quoteLocation + 1), searchLength)].location;
}
*string = [[self string] substringWithRange:NSMakeRange([self scanLocation], (quoteLocation - [self scanLocation]))];
// TODO: process escape sequences out of the string - replacing with their actual characters. a function that does just this belongs
// in another class. So it may make more sense to change this whole implementation to just go character by character instead.
[self setScanLocation:(quoteLocation + 1)];
*/
result = YES;
}
return result;
}
- (BOOL)scanUnicodeCharacterIntoString:(NSMutableString *)string
{
NSString *digits = [[self string] substringWithRange:NSMakeRange([self scanLocation], 4)];
/* START Updated code modified from code fix submitted by Bill Garrison
- March 28, 2006 - http://www.standardorbit.net */
NSScanner *hexScanner = [NSScanner scannerWithString:digits];
NSString *verifiedHexDigits;
NSCharacterSet *hexDigitSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFabcdef"];
if (NO == [hexScanner scanCharactersFromSet:hexDigitSet intoString:&verifiedHexDigits]) {
return NO;
}
if (4 != [verifiedHexDigits length]) {
return NO;
}
// Read in the hex value
[hexScanner setScanLocation:0];
unsigned unicodeHexValue;
if (NO == [hexScanner scanHexInt:&unicodeHexValue]) {
return NO;
}
[string appendFormat:@"%C", unicodeHexValue];
/* END update - March 28, 2006 */
return YES;
}
- (NSUInteger)locationOfString:(NSString *)searchedString
{
// Since we have already scanned white space, we know that we're at the start of some value, and each of the strings
// is at most four characters, so just look ahead that many spaces. (In previous versions of the code, I was scanning
// ahead through the entire string, but this was incredibly expensive for long strings - adding massive amounts of
// time to scan way past the string we might care about)
NSUInteger scanLength = [[self string] length] - [self scanLocation];
scanLength = MIN(scanLength, searchedString.length);
NSRange searchRange = NSMakeRange([self scanLocation], scanLength);
return [[self string] rangeOfString:searchedString options:0 range:searchRange].location;
}
- (BOOL)scanJSONValue:(id *)value
{
BOOL result = NO;
[self scanJSONWhiteSpace];
NSUInteger scanLocation = [self scanLocation];
NSUInteger trueLocation = [self locationOfString:jsonTrueString];
NSUInteger falseLocation = [self locationOfString:jsonFalseString];
NSUInteger nullLocation = [self locationOfString:jsonNullString];
unichar currentCharacter = [[self string] characterAtIndex:scanLocation];
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
NSString *substring = [NSString stringWithFormat: @"%c", currentCharacter];
if ([substring isEqualToString:jsonStringDelimiterString]) {
result = [self scanJSONString:value];
} else if ([substring isEqualToString:jsonObjectStartString]) {
result = [self scanJSONObject:value];
} else if ([substring isEqualToString:jsonArrayStartString]) {
result = [self scanJSONArray:value];
} else if (scanLocation == trueLocation) {
result = YES;
*value = [NSNumber numberWithBool:YES];
[self setScanLocation:(scanLocation + jsonTrueString.length)];
} else if (scanLocation == falseLocation) {
result = YES;
*value = [NSNumber numberWithBool:NO];
[self setScanLocation:(scanLocation + jsonFalseString.length)];
} else if (scanLocation == nullLocation) {
result = YES;
*value = [NSNull null];
[self setScanLocation:(scanLocation + jsonNullString.length)];
} else if (([digits characterIsMember:currentCharacter]) || (currentCharacter == '-')) {
result = [self scanJSONNumber:value];
}
return result;
}
- (BOOL)scanJSONNumber:(NSNumber **)number
{
NSDecimal aDecimal;
BOOL isDecimal = [self scanDecimal:&aDecimal];
if ( isDecimal ) {
*number = [NSDecimalNumber decimalNumberWithDecimal:aDecimal];
}
return isDecimal;
}
- (BOOL)scanJSONWhiteSpace
{
//NSLog(@"Scanning white space - here are the next ten chars ---%@---", [[self string] substringWithRange:NSMakeRange([self scanLocation], 10)]);
BOOL result = NO;
NSCharacterSet *space = [NSCharacterSet whitespaceAndNewlineCharacterSet];
while ([space characterIsMember:[[self string] characterAtIndex:[self scanLocation]]]) {
[self setScanLocation:([self scanLocation] + 1)];
result = YES;
}
//NSLog(@"Done Scanning white space - here are the next ten chars ---%@---", [[self string] substringWithRange:NSMakeRange([self scanLocation], 10)]);
return result;
}
- (BOOL)scanJSONKeyValueSeparator
{
return [self scanString:jsonKeyValueSeparatorString intoString:nil];
}
- (BOOL)scanJSONValueSeparator
{
return [self scanString:jsonValueSeparatorString intoString:nil];
}
- (BOOL)scanJSONObjectStartString
{
return [self scanString:jsonObjectStartString intoString:nil];
}
- (BOOL)scanJSONObjectEndString
{
return [self scanString:jsonObjectEndString intoString:nil];
}
- (BOOL)scanJSONArrayStartString
{
return [self scanString:jsonArrayStartString intoString:nil];
}
- (BOOL)scanJSONArrayEndString
{
return [self scanString:jsonArrayEndString intoString:nil];
}
- (BOOL)scanJSONStringDelimiterString;
{
return [self scanString:jsonStringDelimiterString intoString:nil];
}
@end