开发者

How to use the JSON Parsing?

开发者 https://www.devze.com 2023-02-01 07:36 出处:网络
I am a fresher. I don\'t know how to use JSON for Parsing .I am really very confuse because the tutorial i have read are out dated because apple has deprecated all the API\'s and documents .Thats what

I am a fresher. I don't know how to use JSON for Parsing .I am really very confuse because the tutorial i have read are out dated because apple has deprecated all the API's and documents .Thats what i found开发者_高级运维 .So anyone can give me the start to play with JSON?


You can use SBJSON

You can find code at GITHUB


Here's some links on "Picking the best JSON library":

  • Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
  • Best JSON library to use when developing an iPhone application?

And now for the shameless plug for my own JSON parsing solution, JSONKit:

  • What's the most efficient way of converting a 10 MB JSON response into an NSDictionary?
  • Cocoa JSON parsing libraries, part 2


You need to use third-party code to parse JSON. Three popular libraries/frameworks are:

  • SBJSON, aka json-framework
  • TouchJSON
  • yajl-objc

Choose one of them, download its source code and add it do your project.


You can use your custom framwork for it just as below

                #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

You can use this using below

       -(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");
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消