如何使用JSON解析?

时间:2010-12-29 06:23:48

标签: iphone

我是一个更新鲜的人。我不知道如何使用JSON进行解析。我真的很困惑,因为我读过的教程已经过时了,因为苹果已经弃用了所有的API和文档。这就是我找到的。所以任何人都可以给我开始玩用JSON?

4 个答案:

答案 0 :(得分:1)

您可以使用SBJSON

您可以在GITHUB

找到代码

答案 1 :(得分:1)

答案 2 :(得分:0)

您需要使用第三方代码来解析JSON。三个流行的图书馆/框架是:

选择其中一个,下载其源代码并添加它来完成您的项目。

答案 3 :(得分:0)

您可以使用自定义框架,如下所示

                #import <Foundation/Foundation.h>
            #import "SVProgressHUD.h"
            @protocol JsonDataDelegate <NSObject>

            @required
            - (void) JsonprocessSuccessful: (NSString *)receivedData;
            -(void) JsonprocessFail;
            @end
            @interface JsonRest : NSObject
            {
                id <JsonDataDelegate> delegate;
                NSURLConnection *theConnection;
                NSMutableData *webData;
                BOOL HadGotResponse;
                BOOL HasFailedConnection;
                UIAlertView *alert;
            }
            @property (retain) id delegate;
            @property(nonatomic,retain) NSURLConnection *theConnection;
            @property (nonatomic)BOOL HadGotResponse;
            @property (nonatomic)BOOL HasFailedConnection;
            -(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter;
            -(void)Set2Defaults;

            @end


            #import "JsonRest.h"
            #define BASE_URL @"http://www.abc.com"
            #define DOMAIN @"GETLIST"

            @implementation JsonRest
            @synthesize delegate,HadGotResponse,HasFailedConnection,theConnection;
            - (id)init
            {
                if (self) 
                {
                    // Initialization code.
                    //appdel = (ReachCastAppDelegate*)[[UIApplication sharedApplication]delegate];
                }
                return self;
            }

            -(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter
            {
                [SVProgressHUD startActivity : @"Loading..."];
                NSString *strUrl=[NSString stringWithFormat:@"%@%@?%@",BASE_URL,url,parameter];
                NSURL *url1=[NSURL URLWithString:strUrl];
                NSLog(@"domainURL :: %@",strUrl);
                NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
                [req setTimeoutInterval:60.0];
                [req setHTTPMethod:@"GET"];
                //    if([HttpMethod isEqualToString:@"GET"])
                //    {
                //        [req setHTTPMethod:HttpMethod];
                //        
                //    }
                //    else if([HttpMethod isEqualToString:@"PUT"])
                //    {
                //        NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
                //        
                //        [req setValue:valueforput forHTTPHeaderField:@"Content-type"];
                //        [req setHTTPMethod:HttpMethod];
                //        [req setHTTPBody: requestData];
                //        
                //    }
                //    else if ([HttpMethod isEqualToString:@"POST"]){
                //        
                //        NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
                //        
                //        [req setValue:valueforput forHTTPHeaderField:@"Content-type"];
                //        [req setHTTPMethod:HttpMethod];
                //        [req setHTTPBody: requestData];
                //        
                //    }
                if(theConnection)
                    [self Set2Defaults];
                theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
                if(theConnection)
                    webData=[[NSMutableData data]retain];
                else
                    NSLog(@"Connection Failed !!!");

                NSLog(@"Has got response");
            }
            -(void)Set2Defaults {

                if (webData != nil){
                    [webData release];
                    webData = nil;
                }
                if (theConnection != nil) {
                    [theConnection release];
                    if (theConnection != nil) 
                        theConnection = nil;
                }
            }

            #pragma mark -
            #pragma mark NSURL Connection Delegate methods
            -(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) respons{
                [webData setLength: 0];

                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)respons;
                int statusCode = [httpResponse statusCode];
                NSLog(@"statusCode ---- >> %d",statusCode);
                if (200 != statusCode) {    
                    //    if (401 == statusCode) {
                }
            }


            -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
                [webData appendData:data];
            }

            -(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {

                [SVProgressHUD stopActivity];
                [self Set2Defaults];
                self.HadGotResponse=NO;
                self.HasFailedConnection=YES;

                //    txtWindSpeed.text = @"";
                [[self delegate] JsonprocessFail];
                NSLog(@"Connection Failed!!!");

                //[self HideLoadingDialogue];

                alert = [[[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Internet Connection Failed.Please try again." delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
                //alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, 130);
                NSLog(@"%F",alert.frame.origin.y);
                [alert show];
                alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y+25, alert.frame.size.width, 130);

                //[noConnect release];

                [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerCall) userInfo:nil repeats:NO];
            }

            -(void)timerCall
            {
                [alert dismissWithClickedButtonIndex:0 animated:TRUE];
            }
            -(void)connectionDidFinishLoading:(NSURLConnection *)connection
            {
                [SVProgressHUD stopActivity];
                self.HasFailedConnection=NO;
                NSString *theXML;
                theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSASCIIStringEncoding];
                //NSLog(@"theXML Values : %@", theXML);

                //self.ResponseDict = [theXML JSONValue];


                [[self delegate] JsonprocessSuccessful:theXML];
                [theXML release];
            }

            -(void)dealloc
            {
                if (webData != nil){
                    [webData release];
                    webData = nil;
                }

                if (theConnection != nil) {
                    [theConnection release];
                    if (theConnection != nil) 
                        theConnection = nil;
                }
                [super dealloc];
               // [ResponseDict release];

            }
            @end

您可以使用以下

       -(void)getJsonCalling
            {
            @try {
                NSString *strParameter=[NSString stringWithFormat:@"param1=%@&param2=%@",param1,param2];
                objJsonRest=[[JsonRest alloc]init];
                [objJsonRest setDelegate:self];
                [objJsonRest GetServiceCall:DOMAIN Paraqmeter:strParameter];
                [objJsonRest release];
            }
            @catch (NSException *exception) {
                NSLog(@"Exception in %s %@",__FUNCTION__,exception);

            }
            }
            - (void) JsonprocessSuccessful: (NSString *)receivedData
            {
              }
            -(void) JsonprocessFail;
            {
                   NSLog(@"FAIL");
            }