解析json格式的。m文件
//
// XmlParser.m
// MyKeDuoMA
//
// Created by liqiyang on 11-3-16.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "JsonParser.h"
//#import "PublicFunction.h"
#pragma mark -
typedef enum _EJsonValueType
{
EJsonString = 0,
EJsonArray,
EJsonObject,
EJsonFixedValue,
EJsonNumber
}EJsonValueType;
typedef struct _TJsonStruct
{
NSString* iParam;
NSString* iValue;
NSMutableArray* iChildNodeArray;
EJsonValueType iType;
} TJsonStruct;
@interface CJsonParser (private)
-(id) Decode:(NSRange*)getRange;
-(void) Close:(NSMutableArray*)aJson;
-(int) GetParameterCount:(NSString*)aParameter JsonStructArray:(NSMutableArray*)aJson;
-(BOOL) GetParameterValue:(NSString*)aParameter Value:(NSMutableString*)aValue JsonStructArray:(NSMutableArray*)aJson;
-(unichar) ConsumeCharAt:(int) aIn;
-(void) ConsumeFirst;
-(void) Consume:(int) aInc;
-(void) ConsumeReset:(int) aIndex;
-(int) ConsumeLeft;
-(void) ConsumeSkipSpace;
-(NSRange) ConsumeGetToken:(NSString*)aInvalidChars;
-(BOOL) isObject:(unichar) aChar;
-(BOOL) isArray:(unichar) aChar;
-(BOOL) isNumber:(unichar) aChar;
-(BOOL) isString:(unichar) aChar;
-(BOOL) isFixedValue:(NSString*) aChar;
-(NSRange) parseString;
-(NSRange) parseNumber;
-(id) parseObject;
-(id) parseArray;
-(void) PrintDebug:(NSMutableArray*)aJson Level:(int) aLevel;
@end
@implementation CJsonParser
@synthesize iJsonNodeArray;
@synthesize iLastType;
-(id) init
{
self = [super init];
//iJsonNodeArray = [[NSMutableArray alloc] init];
//iLastType = [[NSMutableArray alloc] init];
iCurIndex = 0;
iJsonString = nil;
return self;
}
- (void)dealloc
{
[self Close: iJsonNodeArray];
iJsonNodeArray = nil;
[iJsonString release];
[iLastType release];
[super dealloc];
}
-(void) ParserJsonText: (NSString*)aJsonString
{
if(aJsonString == nil || [aJsonString length] <=0)
{
iJsonString = @"";
return;
}
if(iJsonNodeArray != nil)
{
[self Close:iJsonNodeArray];
iJsonNodeArray = nil;
}
if(iLastType != nil)
{
[iLastType release];
}
iJsonNodeArray = [[NSMutableArray alloc] init];
iLastType = [[NSMutableArray alloc] init];
if (![iJsonString isEqualToString:aJsonString]) {
[iJsonString release];
iJsonString = [aJsonString retain];
}
//NSLog(@"\n\t***************\n%@***********\n",aJsonString);
iJsonNodeArray = [self Decode:nil];
}
-(int) GetParameterCount: (NSString*)aParameter
{
if (iJsonNodeArray == nil || [iJsonNodeArray count] <= 0)
return 0;
else
return [self GetParameterCount:aParameter JsonStructArray:iJsonNodeArray];
}
-(BOOL) GetParameterValue: (NSString*)aParameter Value:(NSMutableString*)aValue
{
BOOL result = NO;
result = [self GetParameterValue:aParameter Value:aValue JsonStructArray:iJsonNodeArray];
if (result == YES && [aValue length] <=0)
result = NO;
return result;
}
-(id) Decode:(NSRange*)aValue
{
//===============
//NSLog(@"%@", @"Decode");
[self ConsumeSkipSpace];
if ([self isArray:[self ConsumeCharAt:0]])
{
EJsonValueType jvt = EJsonArray;
[iLastType addObject:[NSNumber numberWithInt:jvt]];