2014-11-03 73 views
0

我想用php連接我的iPad應用程序。我的代碼如下:在xcode 5中轉換爲JSON格式

- (IBAction)loginbtn:(id)sender{ 
     NSString *string1 =_text1.text; 
     NSString *string2 =_text2.text; 
     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"myurl"]]; 
     NSString *mystr=[NSString stringWithFormat:@"user1=%@,pwd=%@",string1,string2]; 
     NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url]; 
     [request setHTTPMethod:@"POST"]; 
     [request setHTTPBody:[mystr dataUsingEncoding:NSUTF8StringEncoding]]; 

     NSURLConnection * conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

     if (conn) 
      NSLog(@"Connection Successful"); 
     else 
      NSLog(@"failed"); 

} 

在這裏,我怎麼能轉換成使用NSJsonSerialization JSON格式這一點。誰能幫我?

+0

您是否閱讀過文檔...? – 2014-11-03 10:16:00

回答

0

使用以下方法將對象轉換爲json字符串,並將json字符串轉換爲對象。的NsmutableData

+ (NSString *) getJSONString:(id)object { 

    NSString *jsonString = @""; 
    @try { 
     NSError *error = nil; 
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object 
                  options:NSJSONWritingPrettyPrinted 
                  error:&error]; 
     if (! jsonData) { 
      NSLog(@"Got an error: %@", error); 
     } else { 
      jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
     } 
     return jsonString; 
    } 
    @catch (NSException *exception) { 
     NSLog(@"Exception :%@",exception); 
     return jsonString; 
    } 
} 

//--------------------------------------------------------------- 

+ (id) getObjectFromJSONString:(NSString *)jsonString { 
    @try { 
     NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
     NSError *error = nil; 
     id object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 
     return object; 
    } 
    @catch (NSException *exception) { 
     NSLog(@"Exception :%@",exception);  
     return nil; 
    } 
} 
0

採取對象作爲NSMutableData * webMerchantLoginAndProfileDataIphone;

在connectiondidfinishLoading方法U將得到的數據如下: -

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
[webMerchantLoginAndProfileDataIphone setLength:0]; 
} 

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

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error 
{ 
    [delegate processMerchantLoginAndProfileData:@"error" success:0]; 

    alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You are not connected to the internet. Please check your internet connection and try again." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
[alert show]; 

return; 
} 

-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{ 
    /Check the request and returns the response. 
    //NSLog(@"DONE. Received Bytes get iphone Data: %d", [webMerchantLoginAndProfileDataIphone length]); 
    theXMLMerchantLoginAndProfileDataIphone = [[NSString alloc] 
           initWithBytes: [webMerchantLoginAndProfileDataIphone mutableBytes] 
           length: [webMerchantLoginAndProfileDataIphone length] 
           encoding:NSUTF8StringEncoding]; 

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:theXMLMerchantLoginAndProfileDataIphone options:kNilOptions error:&error]; 

} 
0

首先你必須添加代表爲NSURLConnection<NSURLConnectionDelegate,NSURLConnectionDataDelegate>否則您的代理就不叫。我們將採用webData作爲NSMutableData,所以當您獲得數據響應時,您會將該數據存儲在webData中。

所以.H文件

@interface yourClass : UIViewController<NSURLConnectionDelegate,NSURLConnectionDataDelegate> 
@property(nonatomic,strong)NSMutableData *webData; 

爲實現需要4名代表法這是關係到你的NSURLConnection

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    strError = error.localizedDescription; 
    NSLog(@"Got Error from Server : %@",error.localizedDescription); 
} 
//this method will call once you get data from server so set your data length to 0. 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [self.webData setLength:0]; 
} 
//when receive data from server append that. 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [self.webData appendData:data]; 
} 
//once you get all data this method will be called that your connection is finish. 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // NSLog(@"HTTP RES :\n %@",[[NSString alloc]initWithData:self.webData encoding:NSUTF8StringEncoding]); 

    //check that you get response is in correct format like dictionary or array. 
    NSError *err; 
    id objectChecker = [NSJSONSerialization JSONObjectWithData:self.webData options:NSJSONReadingMutableContainers error:&err]; 

    if ([objectChecker isKindOfClass:[NSArray class]]) 
    { 
     //your response is array. 
    } 
    else if([objectChecker isKindOfClass:[NSDictionary class]]) 
    { 
    //your response is dictionary. 
    } 
    else 
    { 

    } 
} 

也許這會幫助你。