Revision 3ebe9884

b/asi-http-request-with-pithos/Classes/Pithos/ASIPithos.h
46 46
    NSString *authToken;
47 47
    
48 48
    NSString *publicURLPrefix;
49
    
50
    NSString *userCatalogURL;
49 51
}
50 52

  
51 53
@property (strong) NSString *authURL;
......
58 60

  
59 61
@property (strong) NSString *publicURLPrefix;
60 62

  
63
@property (strong) NSString *userCatalogURL;
64

  
61 65
+ (id)pithos;
62 66

  
63 67
- (NSString *)storageURLWithAuthUser:(NSString *)anAuthUser;
b/asi-http-request-with-pithos/Classes/Pithos/ASIPithos.m
38 38
#import "ASIPithosRequest.h"
39 39

  
40 40
@implementation ASIPithos
41
@synthesize authURL, authUser, authKey, storageURLPrefix, storageURL, authToken, publicURLPrefix;
41
@synthesize authURL, authUser, authKey, storageURLPrefix, storageURL, authToken, publicURLPrefix, userCatalogURL;
42 42

  
43 43
#pragma mark - Object Lifecycle
44 44

  
......
48 48
}
49 49

  
50 50
- (NSString *)description {
51
    return [NSString stringWithFormat:@"authURL: %@, authUser: %@, authKey: %@, storageURLPrefix: %@, storageURL: %@, authToken: %@, publicURLPrefix: %@", 
52
            authURL, authUser, authKey, storageURLPrefix, storageURL, authToken, publicURLPrefix];
51
    return [NSString stringWithFormat:@"authURL: %@, authUser: %@, authKey: %@, storageURLPrefix: %@, storageURL: %@, authToken: %@, publicURLPrefix: %@, userCatalogURL: %@",
52
            authURL, authUser, authKey, storageURLPrefix, storageURL, authToken, publicURLPrefix, userCatalogURL];
53 53
}
54 54

  
55 55

  
b/asi-http-request-with-pithos/Classes/Pithos/ASIPithosRequest.h
61 61
+ (id)authenticationRequestWithPithos:(ASIPithos *)pithos;
62 62
+ (ASIPithos *)authenticateWithPithos:(ASIPithos *)pithos error:(NSError **)error;
63 63

  
64
// POST userCatalogURL
65
+ (id)userCatalogRequestWithPithos:(ASIPithos *)pithos displaynames:(NSArray *)displaynames UUIDs:(NSArray *)UUIDs;
66

  
67
- (NSDictionary *)catalogs;
68
- (NSDictionary *)displaynameCatalog;
69
- (NSDictionary *)UUIDCatalog;
70

  
64 71
// GET authURL
65 72
+ (id)listSharingAccountsRequestWithPithos:(ASIPithos *)pithos;
66 73
// GET authURL?[limit=limit]&[marker=marker]
b/asi-http-request-with-pithos/Classes/Pithos/ASIPithosRequest.m
38 38
#import "ASIPithosRequest.h"
39 39
#import "ASIPithos.h"
40 40
#import "ASIPithosAccount.h"
41
#import "SBJson.h"
41 42

  
42 43
@implementation ASIPithosRequest
43 44
@synthesize currentElement, currentContent, currentAccount;
......
100 101
}
101 102

  
102 103
#pragma mark -
104
#pragma mark User Catalog
105

  
106
// POST userCatalogURL
107
+ (id)userCatalogRequestWithPithos:(ASIPithos *)pithos displaynames:(NSArray *)displaynames UUIDs:(NSArray *)UUIDs {
108
    NSString *urlString = [NSString stringWithString:pithos.userCatalogURL];
109
    
110
    ASIPithosRequest *request = [self requestWithURL:[NSURL URLWithString:urlString]];
111
	[request setRequestMethod:@"POST"];
112
    [request addRequestHeader:@"X-Auth-Token" value:pithos.authToken];
113
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
114
    
115
    NSMutableString *dataString = [NSMutableString stringWithString:@"{\"displaynames\":["];
116
    if (displaynames) {
117
        for (NSUInteger index = 0 ; index < displaynames.count ; index++) {
118
            [dataString appendFormat:@"\"%@\"%@",
119
             [[[displaynames objectAtIndex:index] stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]
120
              stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""],
121
             ((index == displaynames.count - 1) ? @"" : @",")];
122
        }
123
    }
124
    [dataString appendFormat:@"],\"uuids\":["];
125
    if (UUIDs) {
126
        for (NSUInteger index = 0 ; index < UUIDs.count ; index++) {
127
            [dataString appendFormat:@"\"%@\"%@", [UUIDs objectAtIndex:index], ((index == UUIDs.count - 1) ? @"" : @",")];
128
        }
129
    }
130
    [dataString appendFormat:@"]}"];
131
    [request appendPostData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
132
    
133
	return request;
134
}
135

  
136
- (NSDictionary *)catalogs {
137
    SBJsonParser *parser = [[SBJsonParser alloc] init];
138
    NSDictionary *catalogs = [parser objectWithString:[self responseString]];
139
    return catalogs;
140
}
141

  
142
- (NSDictionary *)displaynameCatalog {
143
    return [[self catalogs] objectForKey:@"displayname_catalog"];
144
}
145

  
146
- (NSDictionary *)UUIDCatalog {
147
    return [[self catalogs] objectForKey:@"uuid_catalog"];
148
}
149

  
150
#pragma mark -
103 151
#pragma mark GET
104 152

  
105 153
// GET authURL
b/json-framework-3.2.0/.gitattributes
1
# Set default behaviour, in case users don't have core.autocrlf set.
2
* text=auto
3

  
4
# Ignore whitespace in these files
5
Tests/Stream/* binary
b/json-framework-3.2.0/.gitignore
1
# Xcode
2
build/
3
*.pbxuser
4
!default.pbxuser
5
*.mode1v3
6
!default.mode1v3
7
*.mode2v3
8
!default.mode2v3
9
*.perspectivev3
10
!default.perspectivev3
11
*.xcworkspace
12
!default.xcworkspace
13
xcuserdata/
14
profile
15
*.moved-aside
16
DerivedData
17
.idea/
18
.DS_Store
b/json-framework-3.2.0/CREDITS.md
1
Credits
2
=======
3

  
4
My thanks to the following people and organisations, without whom this
5
library wouldn't be what it is today. (Please let me know if I've
6
mistakenly omitted anyone.)
7

  
8
* Alen Zhou
9
* Andrew Hannon
10
* Andrew W. Donoho
11
* Andy Brett
12
* Andy Warwick
13
* Antoine Perdaens
14
* Ben Rimmington
15
* Blake Seely
16
* Cary Yang
17
* David Keegan
18
* Gabriel Handford
19
* George MacKerron
20
* Greg Bolsinga
21
* Hager Hu
22
* Hiroshi Saito
23
* Jakub Jelonek
24
* Jens Alfke
25
* Joerg Schwieder
26
* John Engelhart
27
* Konstantin Welke
28
* Lloyd Hilaiel
29
* Marc Lehmann
30
* Michael Papp
31
* Mike Monaco
32
* Ole André Vadla Ravnås
33
* Phill Baker
34
* Robert McNally
35
* Robin Lu
36
* Ryan Smale
37
* Sam Dean
38
* Sam Soffes
39
* Sean Scanlon
40
* Stig Brautaset
41
* The Adium Crew
42
* Tobias Höhmann
43
* Tod Karpinski
44
* Ullrich Schäfer
45
* Wolfgang Sourdeau
46
* aethereal
47
* boredzo
48
* dewvinci
49
* dmaclach
50
* jinksys
51
* jonkean
52
* lukef
53
* renerattur
54
* upsuper
b/json-framework-3.2.0/Classes/NSObject+SBJson.h
1
/*
2
 Copyright (C) 2009 Stig Brautaset. All rights reserved.
3

  
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6

  
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9

  
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13

  
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17

  
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#import <Foundation/Foundation.h>
31

  
32
#pragma mark JSON Writing
33

  
34
/// Adds JSON generation to NSObject
35
@interface NSObject (NSObject_SBJsonWriting)
36

  
37
/**
38
 Encodes the receiver into a JSON string
39

  
40
 Although defined as a category on NSObject it is only defined for NSArray and NSDictionary.
41

  
42
 @return the receiver encoded in JSON, or nil on error.
43

  
44
 @warning Deprecated in Version 3.2; will be removed in 4.0
45

  
46
 */
47
- (NSString *)JSONRepresentation __attribute__ ((deprecated));
48

  
49
@end
50

  
51

  
52
#pragma mark JSON Parsing
53

  
54
/// Adds JSON parsing methods to NSString
55
@interface NSString (NSString_SBJsonParsing)
56

  
57
/**
58
 Decodes the receiver's JSON text
59

  
60
 @return the NSDictionary or NSArray represented by the receiver, or nil on error.
61

  
62
 @warning Deprecated in Version 3.2; will be removed in 4.0
63

  
64
 */
65
- (id)JSONValue __attribute__ ((deprecated));
66

  
67
@end
68

  
69
/// Adds JSON parsing methods to NSData
70
@interface NSData (NSData_SBJsonParsing)
71

  
72
/**
73
 Decodes the receiver's JSON data
74

  
75
 @return the NSDictionary or NSArray represented by the receiver, or nil on error.
76

  
77
 @warning Deprecated in Version 3.2; will be removed in 4.0
78

  
79
 */
80
- (id)JSONValue __attribute__ ((deprecated));
81

  
82
@end
b/json-framework-3.2.0/Classes/NSObject+SBJson.m
1
/*
2
 Copyright (C) 2009 Stig Brautaset. All rights reserved.
3
 
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6
 
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9
 
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13
 
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17
 
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#if !__has_feature(objc_arc)
31
#error "This source file must be compiled with ARC enabled!"
32
#endif
33

  
34
#import "NSObject+SBJson.h"
35
#import "SBJsonWriter.h"
36
#import "SBJsonParser.h"
37

  
38
@implementation NSObject (NSObject_SBJsonWriting)
39

  
40
- (NSString *)JSONRepresentation {
41
    SBJsonWriter *writer = [[SBJsonWriter alloc] init];    
42
    NSString *json = [writer stringWithObject:self];
43
    if (!json)
44
        NSLog(@"-JSONRepresentation failed. Error is: %@", writer.error);
45
    return json;
46
}
47

  
48
@end
49

  
50

  
51

  
52
@implementation NSString (NSString_SBJsonParsing)
53

  
54
- (id)JSONValue {
55
    SBJsonParser *parser = [[SBJsonParser alloc] init];
56
    id repr = [parser objectWithString:self];
57
    if (!repr)
58
        NSLog(@"-JSONValue failed. Error is: %@", parser.error);
59
    return repr;
60
}
61

  
62
@end
63

  
64

  
65

  
66
@implementation NSData (NSData_SBJsonParsing)
67

  
68
- (id)JSONValue {
69
    SBJsonParser *parser = [[SBJsonParser alloc] init];
70
    id repr = [parser objectWithData:self];
71
    if (!repr)
72
        NSLog(@"-JSONValue failed. Error is: %@", parser.error);
73
    return repr;
74
}
75

  
76
@end
b/json-framework-3.2.0/Classes/SBJson.h
1
/*
2
 Copyright (C) 2009-2011 Stig Brautaset. All rights reserved.
3

  
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6

  
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9

  
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13

  
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17

  
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#import "SBJsonParser.h"
31
#import "SBJsonWriter.h"
32
#import "SBJsonStreamParser.h"
33
#import "SBJsonStreamParserAdapter.h"
34
#import "SBJsonStreamWriter.h"
35
#import "NSObject+SBJson.h"
36

  
b/json-framework-3.2.0/Classes/SBJsonParser.h
1
/*
2
 Copyright (C) 2009 Stig Brautaset. All rights reserved.
3

  
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6

  
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9

  
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13

  
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17

  
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#import <Foundation/Foundation.h>
31

  
32
/**
33
 Parse JSON Strings and NSData objects
34

  
35
 This uses SBJsonStreamParser internally.
36

  
37
 */
38

  
39
@interface SBJsonParser : NSObject
40

  
41
/**
42
 The maximum recursing depth.
43

  
44
 Defaults to 32. If the input is nested deeper than this the input will be deemed to be
45
 malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can
46
 turn off this security feature by setting the maxDepth value to 0.
47
 */
48
@property NSUInteger maxDepth;
49

  
50
/**
51
 Description of parse error
52

  
53
 This method returns the trace of the last method that failed.
54
 You need to check the return value of the call you're making to figure out
55
 if the call actually failed, before you know call this method.
56

  
57
 @return A string describing the error encountered, or nil if no error occured.
58

  
59
 */
60
@property(copy) NSString *error;
61

  
62
/**
63
 Return the object represented by the given NSData object.
64

  
65
 The data *must* be UTF8 encoded.
66

  
67
 @param data An NSData containing UTF8 encoded data to parse.
68
 @return The NSArray or NSDictionary represented by the object, or nil if an error occured.
69

  
70
 */
71
- (id)objectWithData:(NSData*)data;
72

  
73
/**
74
 Return the object represented by the given string
75

  
76
 This method converts its input to an NSData object containing UTF8 and calls -objectWithData: with it.
77

  
78
 @return The NSArray or NSDictionary represented by the object, or nil if an error occured.
79
 */
80
- (id)objectWithString:(NSString *)repr;
81

  
82
/**
83
 Return the object represented by the given string
84

  
85
 This method calls objectWithString: internally. If an error occurs, and if error
86
 is not nil, it creates an NSError object and returns this through its second argument.
87

  
88
 @param jsonText the json string to parse
89
 @param error pointer to an NSError object to populate on error
90

  
91
 @return The NSArray or NSDictionary represented by the object, or nil if an error occured.
92

  
93
 @warning Deprecated in Version 3.2; will be removed in 4.0
94

  
95
 */
96

  
97
- (id)objectWithString:(NSString*)jsonText
98
                 error:(NSError**)error __attribute__ ((deprecated));
99

  
100
@end
101

  
102

  
b/json-framework-3.2.0/Classes/SBJsonParser.m
1
/*
2
 Copyright (C) 2009,2010 Stig Brautaset. All rights reserved.
3
 
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6
 
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9
 
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13
 
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17
 
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#if !__has_feature(objc_arc)
31
#error "This source file must be compiled with ARC enabled!"
32
#endif
33

  
34
#import "SBJsonParser.h"
35
#import "SBJsonStreamParser.h"
36
#import "SBJsonStreamParserAdapter.h"
37
#import "SBJsonStreamParserAccumulator.h"
38

  
39
@implementation SBJsonParser
40

  
41
@synthesize maxDepth;
42
@synthesize error;
43

  
44
- (id)init {
45
    self = [super init];
46
    if (self)
47
        self.maxDepth = 32u;
48
    return self;
49
}
50

  
51

  
52
#pragma mark Methods
53

  
54
- (id)objectWithData:(NSData *)data {
55

  
56
    if (!data) {
57
        self.error = @"Input was 'nil'";
58
        return nil;
59
    }
60

  
61
	SBJsonStreamParserAccumulator *accumulator = [[SBJsonStreamParserAccumulator alloc] init];
62
    
63
    SBJsonStreamParserAdapter *adapter = [[SBJsonStreamParserAdapter alloc] init];
64
    adapter.delegate = accumulator;
65
	
66
	SBJsonStreamParser *parser = [[SBJsonStreamParser alloc] init];
67
	parser.maxDepth = self.maxDepth;
68
	parser.delegate = adapter;
69
	
70
	switch ([parser parse:data]) {
71
		case SBJsonStreamParserComplete:
72
            return accumulator.value;
73
			break;
74
			
75
		case SBJsonStreamParserWaitingForData:
76
		    self.error = @"Unexpected end of input";
77
			break;
78

  
79
		case SBJsonStreamParserError:
80
		    self.error = parser.error;
81
			break;
82
	}
83
	
84
	return nil;
85
}
86

  
87
- (id)objectWithString:(NSString *)repr {
88
	return [self objectWithData:[repr dataUsingEncoding:NSUTF8StringEncoding]];
89
}
90

  
91
- (id)objectWithString:(NSString*)repr error:(NSError**)error_ {
92
	id tmp = [self objectWithString:repr];
93
    if (tmp)
94
        return tmp;
95
    
96
    if (error_) {
97
		NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:error, NSLocalizedDescriptionKey, nil];
98
        *error_ = [NSError errorWithDomain:@"org.brautaset.SBJsonParser.ErrorDomain" code:0 userInfo:ui];
99
	}
100
	
101
    return nil;
102
}
103

  
104
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParser.h
1
/*
2
 Copyright (c) 2010, Stig Brautaset.
3
 All rights reserved.
4

  
5
 Redistribution and use in source and binary forms, with or without
6
 modification, are permitted provided that the following conditions are
7
 met:
8

  
9
   Redistributions of source code must retain the above copyright
10
   notice, this list of conditions and the following disclaimer.
11

  
12
   Redistributions in binary form must reproduce the above copyright
13
   notice, this list of conditions and the following disclaimer in the
14
   documentation and/or other materials provided with the distribution.
15

  
16
   Neither the name of the the author nor the names of its contributors
17
   may be used to endorse or promote products derived from this software
18
   without specific prior written permission.
19

  
20
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21
 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22
 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
 */
32

  
33
#import <Foundation/Foundation.h>
34

  
35
@class SBJsonTokeniser;
36
@class SBJsonStreamParser;
37
@class SBJsonStreamParserState;
38

  
39
typedef enum {
40
	SBJsonStreamParserComplete,
41
	SBJsonStreamParserWaitingForData,
42
	SBJsonStreamParserError,
43
} SBJsonStreamParserStatus;
44

  
45

  
46
/**
47
 Delegate for interacting directly with the stream parser
48

  
49
 You will most likely find it much more convenient to implement the
50
 SBJsonStreamParserAdapterDelegate protocol instead.
51
 */
52
@protocol SBJsonStreamParserDelegate
53

  
54
/// Called when object start is found
55
- (void)parserFoundObjectStart:(SBJsonStreamParser*)parser;
56

  
57
/// Called when object key is found
58
- (void)parser:(SBJsonStreamParser*)parser foundObjectKey:(NSString*)key;
59

  
60
/// Called when object end is found
61
- (void)parserFoundObjectEnd:(SBJsonStreamParser*)parser;
62

  
63
/// Called when array start is found
64
- (void)parserFoundArrayStart:(SBJsonStreamParser*)parser;
65

  
66
/// Called when array end is found
67
- (void)parserFoundArrayEnd:(SBJsonStreamParser*)parser;
68

  
69
/// Called when a boolean value is found
70
- (void)parser:(SBJsonStreamParser*)parser foundBoolean:(BOOL)x;
71

  
72
/// Called when a null value is found
73
- (void)parserFoundNull:(SBJsonStreamParser*)parser;
74

  
75
/// Called when a number is found
76
- (void)parser:(SBJsonStreamParser*)parser foundNumber:(NSNumber*)num;
77

  
78
/// Called when a string is found
79
- (void)parser:(SBJsonStreamParser*)parser foundString:(NSString*)string;
80

  
81
@end
82

  
83

  
84
/**
85
 Parse a stream of JSON data.
86

  
87
 Using this class directly you can reduce the apparent latency for each
88
 download/parse cycle of documents over a slow connection. You can start
89
 parsing *and return chunks of the parsed document* before the entire
90
 document is downloaded.
91

  
92
 Using this class is also useful to parse huge documents on disk
93
 bit by bit so you don't have to keep them all in memory.
94

  
95
 JSON is mapped to Objective-C types in the following way:
96

  
97
 - null    -> NSNull
98
 - string  -> NSString
99
 - array   -> NSMutableArray
100
 - object  -> NSMutableDictionary
101
 - true    -> NSNumber's -numberWithBool:YES
102
 - false   -> NSNumber's -numberWithBool:NO
103
 - integer up to 19 digits -> NSNumber's -numberWithLongLong:
104
 - all other numbers       -> NSDecimalNumber
105

  
106
 Since Objective-C doesn't have a dedicated class for boolean values,
107
 these turns into NSNumber instances. However, since these are
108
 initialised with the -initWithBool: method they round-trip back to JSON
109
 properly. In other words, they won't silently suddenly become 0 or 1;
110
 they'll be represented as 'true' and 'false' again.
111

  
112
 As an optimisation integers up to 19 digits in length (the max length
113
 for signed long long integers) turn into NSNumber instances, while
114
 complex ones turn into NSDecimalNumber instances. We can thus avoid any
115
 loss of precision as JSON allows ridiculously large numbers.
116

  
117
 See also SBJsonStreamParserAdapter for more information.
118

  
119
 */
120
@interface SBJsonStreamParser : NSObject {
121
@private
122
	SBJsonTokeniser *tokeniser;
123
}
124

  
125
@property (nonatomic, unsafe_unretained) SBJsonStreamParserState *state; // Private
126
@property (nonatomic, readonly, strong) NSMutableArray *stateStack; // Private
127

  
128
/**
129
 Expect multiple documents separated by whitespace
130

  
131
 Normally the -parse: method returns SBJsonStreamParserComplete when it's found a complete JSON document.
132
 Attempting to parse any more data at that point is considered an error. ("Garbage after JSON".)
133

  
134
 If you set this property to true the parser will never return SBJsonStreamParserComplete. Rather,
135
 once an object is completed it will expect another object to immediately follow, separated
136
 only by (optional) whitespace.
137

  
138
 */
139
@property BOOL supportMultipleDocuments;
140

  
141
/**
142
 Delegate to receive messages
143

  
144
 The object set here receives a series of messages as the parser breaks down the JSON stream
145
 into valid tokens.
146

  
147
 Usually this should be an instance of SBJsonStreamParserAdapter, but you can
148
 substitute your own implementation of the SBJsonStreamParserDelegate protocol if you need to.
149
 */
150
@property (unsafe_unretained) id<SBJsonStreamParserDelegate> delegate;
151

  
152
/**
153
 The max parse depth
154

  
155
 If the input is nested deeper than this the parser will halt parsing and return an error.
156

  
157
 Defaults to 32.
158
 */
159
@property NSUInteger maxDepth;
160

  
161
/// Holds the error after SBJsonStreamParserError was returned
162
@property (copy) NSString *error;
163

  
164
/**
165
 Parse some JSON
166

  
167
 The JSON is assumed to be UTF8 encoded. This can be a full JSON document, or a part of one.
168

  
169
 @param data An NSData object containing the next chunk of JSON
170

  
171
 @return
172
 - SBJsonStreamParserComplete if a full document was found
173
 - SBJsonStreamParserWaitingForData if a partial document was found and more data is required to complete it
174
 - SBJsonStreamParserError if an error occured. (See the error property for details in this case.)
175

  
176
 */
177
- (SBJsonStreamParserStatus)parse:(NSData*)data;
178

  
179
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParser.m
1
/*
2
 Copyright (c) 2010, Stig Brautaset.
3
 All rights reserved.
4

  
5
 Redistribution and use in source and binary forms, with or without
6
 modification, are permitted provided that the following conditions are
7
 met:
8

  
9
 Redistributions of source code must retain the above copyright
10
 notice, this list of conditions and the following disclaimer.
11

  
12
 Redistributions in binary form must reproduce the above copyright
13
 notice, this list of conditions and the following disclaimer in the
14
 documentation and/or other materials provided with the distribution.
15

  
16
 Neither the name of the the author nor the names of its contributors
17
 may be used to endorse or promote products derived from this software
18
 without specific prior written permission.
19

  
20
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21
 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22
 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
 */
32

  
33
#if !__has_feature(objc_arc)
34
#error "This source file must be compiled with ARC enabled!"
35
#endif
36

  
37
#import "SBJsonStreamParser.h"
38
#import "SBJsonTokeniser.h"
39
#import "SBJsonStreamParserState.h"
40

  
41
@implementation SBJsonStreamParser
42

  
43
@synthesize supportMultipleDocuments;
44
@synthesize error;
45
@synthesize delegate;
46
@synthesize maxDepth;
47
@synthesize state;
48
@synthesize stateStack;
49

  
50
#pragma mark Housekeeping
51

  
52
- (id)init {
53
	self = [super init];
54
	if (self) {
55
		maxDepth = 32u;
56
        stateStack = [[NSMutableArray alloc] initWithCapacity:maxDepth];
57
        state = [SBJsonStreamParserStateStart sharedInstance];
58
		tokeniser = [[SBJsonTokeniser alloc] init];
59
	}
60
	return self;
61
}
62

  
63

  
64
#pragma mark Methods
65

  
66
- (NSString*)tokenName:(sbjson_token_t)token {
67
	switch (token) {
68
		case sbjson_token_array_start:
69
			return @"start of array";
70
			break;
71

  
72
		case sbjson_token_array_end:
73
			return @"end of array";
74
			break;
75

  
76
		case sbjson_token_number:
77
			return @"number";
78
			break;
79

  
80
		case sbjson_token_string:
81
			return @"string";
82
			break;
83

  
84
		case sbjson_token_true:
85
		case sbjson_token_false:
86
			return @"boolean";
87
			break;
88

  
89
		case sbjson_token_null:
90
			return @"null";
91
			break;
92

  
93
		case sbjson_token_keyval_separator:
94
			return @"key-value separator";
95
			break;
96

  
97
		case sbjson_token_separator:
98
			return @"value separator";
99
			break;
100

  
101
		case sbjson_token_object_start:
102
			return @"start of object";
103
			break;
104

  
105
		case sbjson_token_object_end:
106
			return @"end of object";
107
			break;
108

  
109
		case sbjson_token_eof:
110
		case sbjson_token_error:
111
			break;
112
	}
113
	NSAssert(NO, @"Should not get here");
114
	return @"<aaiiie!>";
115
}
116

  
117
- (void)maxDepthError {
118
    self.error = [NSString stringWithFormat:@"Input depth exceeds max depth of %lu", (unsigned long)maxDepth];
119
    self.state = [SBJsonStreamParserStateError sharedInstance];
120
}
121

  
122
- (void)handleObjectStart {
123
	if (stateStack.count >= maxDepth) {
124
        [self maxDepthError];
125
        return;
126
	}
127

  
128
    [delegate parserFoundObjectStart:self];
129
    [stateStack addObject:state];
130
    self.state = [SBJsonStreamParserStateObjectStart sharedInstance];
131
}
132

  
133
- (void)handleObjectEnd: (sbjson_token_t) tok  {
134
    self.state = [stateStack lastObject];
135
    [stateStack removeLastObject];
136
    [state parser:self shouldTransitionTo:tok];
137
    [delegate parserFoundObjectEnd:self];
138
}
139

  
140
- (void)handleArrayStart {
141
	if (stateStack.count >= maxDepth) {
142
        [self maxDepthError];
143
        return;
144
    }
145
	
146
	[delegate parserFoundArrayStart:self];
147
    [stateStack addObject:state];
148
    self.state = [SBJsonStreamParserStateArrayStart sharedInstance];
149
}
150

  
151
- (void)handleArrayEnd: (sbjson_token_t) tok  {
152
    self.state = [stateStack lastObject];
153
    [stateStack removeLastObject];
154
    [state parser:self shouldTransitionTo:tok];
155
    [delegate parserFoundArrayEnd:self];
156
}
157

  
158
- (void) handleTokenNotExpectedHere: (sbjson_token_t) tok  {
159
    NSString *tokenName = [self tokenName:tok];
160
    NSString *stateName = [state name];
161

  
162
    self.error = [NSString stringWithFormat:@"Token '%@' not expected %@", tokenName, stateName];
163
    self.state = [SBJsonStreamParserStateError sharedInstance];
164
}
165

  
166
- (SBJsonStreamParserStatus)parse:(NSData *)data_ {
167
    @autoreleasepool {
168
        [tokeniser appendData:data_];
169
        
170
        for (;;) {
171
            
172
            if ([state isError])
173
                return SBJsonStreamParserError;
174
            
175
            NSObject *token;
176
            sbjson_token_t tok = [tokeniser getToken:&token];
177
            switch (tok) {
178
                case sbjson_token_eof:
179
                    return [state parserShouldReturn:self];
180
                    break;
181
                    
182
                case sbjson_token_error:
183
                    self.state = [SBJsonStreamParserStateError sharedInstance];
184
                    self.error = tokeniser.error;
185
                    return SBJsonStreamParserError;
186
                    break;
187
                    
188
                default:
189
                    
190
                    if (![state parser:self shouldAcceptToken:tok]) {
191
                        [self handleTokenNotExpectedHere: tok];
192
                        return SBJsonStreamParserError;
193
                    }
194
                    
195
                    switch (tok) {
196
                        case sbjson_token_object_start:
197
                            [self handleObjectStart];
198
                            break;
199
                            
200
                        case sbjson_token_object_end:
201
                            [self handleObjectEnd: tok];
202
                            break;
203
                            
204
                        case sbjson_token_array_start:
205
                            [self handleArrayStart];
206
                            break;
207
                            
208
                        case sbjson_token_array_end:
209
                            [self handleArrayEnd: tok];
210
                            break;
211
                            
212
                        case sbjson_token_separator:
213
                        case sbjson_token_keyval_separator:
214
                            [state parser:self shouldTransitionTo:tok];
215
                            break;
216
                            
217
                        case sbjson_token_true:
218
                            [delegate parser:self foundBoolean:YES];
219
                            [state parser:self shouldTransitionTo:tok];
220
                            break;
221
                            
222
                        case sbjson_token_false:
223
                            [delegate parser:self foundBoolean:NO];
224
                            [state parser:self shouldTransitionTo:tok];
225
                            break;
226
                            
227
                        case sbjson_token_null:
228
                            [delegate parserFoundNull:self];
229
                            [state parser:self shouldTransitionTo:tok];
230
                            break;
231
                            
232
                        case sbjson_token_number:
233
                            [delegate parser:self foundNumber:(NSNumber*)token];
234
                            [state parser:self shouldTransitionTo:tok];
235
                            break;
236
                            
237
                        case sbjson_token_string:
238
                            if ([state needKey])
239
                                [delegate parser:self foundObjectKey:(NSString*)token];
240
                            else
241
                                [delegate parser:self foundString:(NSString*)token];
242
                            [state parser:self shouldTransitionTo:tok];
243
                            break;
244
                            
245
                        default:
246
                            break;
247
                    }
248
                    break;
249
            }
250
        }
251
        return SBJsonStreamParserComplete;
252
    }
253
}
254

  
255
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParserAccumulator.h
1
/*
2
 Copyright (C) 2011 Stig Brautaset. All rights reserved.
3
 
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6
 
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9
 
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13
 
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17
 
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#import <Foundation/Foundation.h>
31
#import "SBJsonStreamParserAdapter.h"
32

  
33
@interface SBJsonStreamParserAccumulator : NSObject <SBJsonStreamParserAdapterDelegate>
34

  
35
@property (copy) id value;
36

  
37
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParserAccumulator.m
1
/*
2
 Copyright (C) 2011 Stig Brautaset. All rights reserved.
3
 
4
 Redistribution and use in source and binary forms, with or without
5
 modification, are permitted provided that the following conditions are met:
6
 
7
 * Redistributions of source code must retain the above copyright notice, this
8
   list of conditions and the following disclaimer.
9
 
10
 * Redistributions in binary form must reproduce the above copyright notice,
11
   this list of conditions and the following disclaimer in the documentation
12
   and/or other materials provided with the distribution.
13
 
14
 * Neither the name of the author nor the names of its contributors may be used
15
   to endorse or promote products derived from this software without specific
16
   prior written permission.
17
 
18
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

  
30
#if !__has_feature(objc_arc)
31
#error "This source file must be compiled with ARC enabled!"
32
#endif
33

  
34
#import "SBJsonStreamParserAccumulator.h"
35

  
36
@implementation SBJsonStreamParserAccumulator
37

  
38
@synthesize value;
39

  
40

  
41
#pragma mark SBJsonStreamParserAdapterDelegate
42

  
43
- (void)parser:(SBJsonStreamParser*)parser foundArray:(NSArray *)array {
44
	value = array;
45
}
46

  
47
- (void)parser:(SBJsonStreamParser*)parser foundObject:(NSDictionary *)dict {
48
	value = dict;
49
}
50

  
51
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParserAdapter.h
1
/*
2
 Copyright (c) 2010, Stig Brautaset.
3
 All rights reserved.
4
 
5
 Redistribution and use in source and binary forms, with or without
6
 modification, are permitted provided that the following conditions are
7
 met:
8
 
9
   Redistributions of source code must retain the above copyright
10
   notice, this list of conditions and the following disclaimer.
11
  
12
   Redistributions in binary form must reproduce the above copyright
13
   notice, this list of conditions and the following disclaimer in the
14
   documentation and/or other materials provided with the distribution.
15
 
16
   Neither the name of the the author nor the names of its contributors
17
   may be used to endorse or promote products derived from this software
18
   without specific prior written permission.
19
 
20
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21
 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22
 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
 */
32

  
33
#import <Foundation/Foundation.h>
34
#import "SBJsonStreamParser.h"
35

  
36
typedef enum {
37
	SBJsonStreamParserAdapterNone,
38
	SBJsonStreamParserAdapterArray,
39
	SBJsonStreamParserAdapterObject,
40
} SBJsonStreamParserAdapterType;
41

  
42
/**
43
 Delegate for getting objects & arrays from the stream parser adapter
44

  
45
 */
46
@protocol SBJsonStreamParserAdapterDelegate
47

  
48
/**
49
 Called if a JSON array is found
50
 
51
 This method is called if a JSON array is found.
52
 
53
 */
54
- (void)parser:(SBJsonStreamParser*)parser foundArray:(NSArray*)array;
55

  
56
/**
57
 Called when a JSON object is found
58

  
59
 This method is called if a JSON object is found.
60
 */
61
- (void)parser:(SBJsonStreamParser*)parser foundObject:(NSDictionary*)dict;
62

  
63
@end
64

  
65
/**
66
 SBJsonStreamParserDelegate protocol adapter
67

  
68
 Rather than implementing the SBJsonStreamParserDelegate protocol yourself you will
69
 most likely find it much more convenient to use an instance of this class and
70
 implement the SBJsonStreamParserAdapterDelegate protocol instead.
71

  
72
 The default behaviour is that the delegate only receives one call from
73
 either the -parser:foundArray: or -parser:foundObject: method when the
74
 document is fully parsed. However, if your inputs contains multiple JSON
75
 documents and you set the parser's -supportMultipleDocuments property to YES
76
 you will get one call for each full method.
77

  
78
     SBJsonStreamParserAdapter *adapter = [[[SBJsonStreamParserAdapter alloc] init] autorelease];
79
     adapter.delegate = self;
80

  
81
     SBJsonStreamParser *parser = [[[SBJsonStreamParser alloc] init] autorelease];
82
     parser.delegate = adapter;
83
     parser.supportMultipleDocuments = YES;
84

  
85
     // Note that this input contains multiple top-level JSON documents
86
     NSData *json = [@"[]{}[]{}" dataWithEncoding:NSUTF8StringEncoding];
87
     [parser parse:data];
88

  
89
 In the above example self will have the following sequence of methods called on it:
90

  
91
 - -parser:foundArray:
92
 - -parser:foundObject:
93
 - -parser:foundArray:
94
 - -parser:foundObject:
95

  
96
 Often you won't have control over the input you're parsing, so can't make use of
97
 this feature. But, all is not lost: this class will let you get the same effect by
98
 allowing you to skip one or more of the outer enclosing objects. Thus, the next
99
 example results in the same sequence of -parser:foundArray: / -parser:foundObject:
100
 being called on your delegate.
101

  
102
     SBJsonStreamParserAdapter *adapter = [[[SBJsonStreamParserAdapter alloc] init] autorelease];
103
     adapter.delegate = self;
104
     adapter.levelsToSkip = 1;
105

  
106
     SBJsonStreamParser *parser = [[[SBJsonStreamParser alloc] init] autorelease];
107
     parser.delegate = adapter;
108

  
109
     // Note that this input contains A SINGLE top-level document
110
     NSData *json = [@"[[],{},[],{}]" dataWithEncoding:NSUTF8StringEncoding];
111
     [parser parse:data];
112

  
113
*/
114
@interface SBJsonStreamParserAdapter : NSObject <SBJsonStreamParserDelegate> {
115
@private
116
	NSUInteger depth;
117
    NSMutableArray *array;
118
	NSMutableDictionary *dict;
119
	NSMutableArray *keyStack;
120
	NSMutableArray *stack;
121
	
122
	SBJsonStreamParserAdapterType currentType;
123
}
124

  
125
/**
126
 How many levels to skip
127
 
128
 This is useful for parsing huge JSON documents, or documents coming in over a very slow link.
129
 
130
 If you set this to N it will skip the outer N levels and call the -parser:foundArray:
131
 or -parser:foundObject: methods for each of the inner objects, as appropriate.
132

  
133
*/
134
@property NSUInteger levelsToSkip;
135

  
136
/**
137
 Your delegate object
138
 Set this to the object you want to receive the SBJsonStreamParserAdapterDelegate messages.
139
 */
140
@property (unsafe_unretained) id<SBJsonStreamParserAdapterDelegate> delegate;
141

  
142
@end
b/json-framework-3.2.0/Classes/SBJsonStreamParserAdapter.m
1
/*
2
 Copyright (c) 2010, Stig Brautaset.
3
 All rights reserved.
4
 
5
 Redistribution and use in source and binary forms, with or without
6
 modification, are permitted provided that the following conditions are
7
 met:
8
 
9
   Redistributions of source code must retain the above copyright
10
   notice, this list of conditions and the following disclaimer.
11
  
12
   Redistributions in binary form must reproduce the above copyright
13
   notice, this list of conditions and the following disclaimer in the
14
   documentation and/or other materials provided with the distribution.
15
 
16
   Neither the name of the the author nor the names of its contributors
17
   may be used to endorse or promote products derived from this software
18
   without specific prior written permission.
19
 
20
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21
 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22
 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
 */
32

  
33
#if !__has_feature(objc_arc)
34
#error "This source file must be compiled with ARC enabled!"
35
#endif
36

  
37
#import "SBJsonStreamParserAdapter.h"
38

  
39
@interface SBJsonStreamParserAdapter ()
40

  
41
- (void)pop;
42
- (void)parser:(SBJsonStreamParser*)parser found:(id)obj;
43

  
44
@end
45

  
46

  
47

  
48
@implementation SBJsonStreamParserAdapter
49

  
50
@synthesize delegate;
51
@synthesize levelsToSkip;
52

  
53
#pragma mark Housekeeping
54

  
55
- (id)init {
56
	self = [super init];
57
	if (self) {
58
		keyStack = [[NSMutableArray alloc] initWithCapacity:32];
59
		stack = [[NSMutableArray alloc] initWithCapacity:32];
60
		
61
		currentType = SBJsonStreamParserAdapterNone;
62
	}
63
	return self;
64
}	
65

  
66

  
67
#pragma mark Private methods
68

  
69
- (void)pop {
70
	[stack removeLastObject];
71
	array = nil;
72
	dict = nil;
73
	currentType = SBJsonStreamParserAdapterNone;
74
	
75
	id value = [stack lastObject];
76
	
77
	if ([value isKindOfClass:[NSArray class]]) {
78
		array = value;
79
		currentType = SBJsonStreamParserAdapterArray;
80
	} else if ([value isKindOfClass:[NSDictionary class]]) {
81
		dict = value;
82
		currentType = SBJsonStreamParserAdapterObject;
83
	}
84
}
85

  
86
- (void)parser:(SBJsonStreamParser*)parser found:(id)obj {
87
	NSParameterAssert(obj);
88
	
89
	switch (currentType) {
90
		case SBJsonStreamParserAdapterArray:
91
			[array addObject:obj];
92
			break;
93

  
94
		case SBJsonStreamParserAdapterObject:
95
			NSParameterAssert(keyStack.count);
96
			[dict setObject:obj forKey:[keyStack lastObject]];
97
			[keyStack removeLastObject];
98
			break;
99
			
100
		case SBJsonStreamParserAdapterNone:
101
			if ([obj isKindOfClass:[NSArray class]]) {
102
				[delegate parser:parser foundArray:obj];
103
			} else {
104
				[delegate parser:parser foundObject:obj];
105
			}				
106
			break;
107

  
108
		default:
109
			break;
110
	}
111
}
112

  
113

  
114
#pragma mark Delegate methods
115

  
116
- (void)parserFoundObjectStart:(SBJsonStreamParser*)parser {
117
	if (++depth > self.levelsToSkip) {
118
		dict = [NSMutableDictionary new];
119
		[stack addObject:dict];
120
		currentType = SBJsonStreamParserAdapterObject;
121
	}
122
}
123

  
124
- (void)parser:(SBJsonStreamParser*)parser foundObjectKey:(NSString*)key_ {
125
	[keyStack addObject:key_];
126
}
127

  
128
- (void)parserFoundObjectEnd:(SBJsonStreamParser*)parser {
129
	if (depth-- > self.levelsToSkip) {
130
		id value = dict;
131
		[self pop];
132
		[self parser:parser found:value];
133
	}
134
}
135

  
136
- (void)parserFoundArrayStart:(SBJsonStreamParser*)parser {
137
	if (++depth > self.levelsToSkip) {
138
		array = [NSMutableArray new];
139
		[stack addObject:array];
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff