在xcode 5中转换为JSON格式

时间:2014-11-03 10:14:00

标签: php ios json xcode

我想用php连接我的iPad应用程序。我的代码如下:

 - (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格式。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

使用以下方法将对象转换为json字符串,将json字符串转换为对象。

+ (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;
    }
}

答案 1 :(得分:0)

NsmutableData的对象作为 NSMutableData * webMerchantLoginAndProfileDataIphone;

在connectiondidfinishLoading方法中,你将获得如下数据: -

-(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];

}

答案 2 :(得分: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
    {

    }
}

也许这会对你有帮助。