SBJson庫解析(六)SBJsonParser


json解析器

 1 /**
2 json轉objc
3 解析json字符串和NSData對象
4 內部使用了SBJsonStreamParser類
5 */
6
7 @interface SBJsonParser : NSObject
8
9 /**
10 @最大遞歸深度,默認為32
11 如果嵌套的太深,大於32被視為惡意解析,返回nil,並發送一個錯誤信號
12 可以通過設置maxDepth為0,來取消此安全功能
13 */
14 @property NSUInteger maxDepth;
15
16 /**
17 @返回一個出錯信息,如果沒錯誤,返回為nil
18 */
19 @property(copy) NSString *error;
20
21 /**
22 json轉objc
23 @返回給定的NSData所代表的對象
24 參數data必須為UTF8編碼
25 返回NSArray或NSDictionary對象,如果返回nil,表示出現錯誤
26 */
27 - (id)objectWithData:(NSData*)data;
28
29 /**
30 json轉objc
31 @返回給定字符串所代表的對象
32 此方法內部實現是:把參數用UTF8編碼成NSData,然后調用objectWithData:方法,轉成NSArray或NSDictionary,或nil
33 */
34 - (id)objectWithString:(NSString *)repr;
35
36 /**
37 json轉objc
38 @返回給定字符串所代表的對象
39 */
40
41 - (id)objectWithString:(NSString*)jsonText
42 error:(NSError**)error;
43
44 @end

實現在SBJsonParser.m文件中:

 1 #import "SBJsonParser.h"
2 #import "SBJsonStreamParser.h"
3 #import "SBJsonStreamParserAdapter.h"
4 #import "SBJsonStreamParserAccumulator.h"
5
6 @implementation SBJsonParser
7
8 @synthesize maxDepth;
9 @synthesize error;
10
11 - (id)init {
12 self = [super init];
13 if (self)
14 self.maxDepth = 32u;
15 return self;
16 }
17
18 #pragma mark Methods
19
20 /**
21 調用流解析器SBJsonStreamParser的parse:方法,把NSData轉成NSArray或NSDictionary對象
22 */
23 - (id)objectWithData:(NSData *)data {
24
25 if (!data) {
26 self.error = @"Input was 'nil'";
27 return nil;
28 }
29
30 //初始化一個json流解析疊加器
31 SBJsonStreamParserAccumulator *accumulator = [[SBJsonStreamParserAccumulator alloc] init];
32
33 //初始化一個json流解析配置器
34 SBJsonStreamParserAdapter *adapter = [[SBJsonStreamParserAdapter alloc] init];
35 //把疊加器設為配置器的代理(delegate)
36 adapter.delegate = accumulator;
37
38 //初始化一個json流解析器,設置參數
39 SBJsonStreamParser *parser = [[SBJsonStreamParser alloc] init];
40 parser.maxDepth = self.maxDepth;
41 //把配置器設為解析器的代理(delegate)
42 parser.delegate = adapter;
43
44 switch ([parser parse:data]) {
45 case SBJsonStreamParserComplete:
46 return accumulator.value;
47 break;
48
49 case SBJsonStreamParserWaitingForData:
50 self.error = @"Unexpected end of input";
51 break;
52
53 case SBJsonStreamParserError:
54 self.error = parser.error;
55 break;
56 }
57
58 return nil;
59 }
60
61 //NSString用UTF8編碼成NSData,再把NSData轉成NSArray或NSDictionary對象
62 - (id)objectWithString:(NSString *)repr {
63 return [self objectWithData:[repr dataUsingEncoding:NSUTF8StringEncoding]];
64 }
65
66 - (id)objectWithString:(NSString*)repr error:(NSError**)error_ {
67 id tmp = [self objectWithString:repr];
68 if (tmp)
69 return tmp;
70
71 if (error_) {
72 NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:error, NSLocalizedDescriptionKey, nil];
73 *error_ = [NSError errorWithDomain:@"org.brautaset.SBJsonParser.ErrorDomain" code:0 userInfo:ui];
74 }
75
76 return nil;
77 }
78
79 @end





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM