如何在JSON中将字典作为参数传递

时间:2014-12-09 05:34:26

标签: ios objective-c

我是json的新手,我想将字典作为参数与url一起传递给服务器,如何在方法发布时完成它? Ihad尝试了示例代码但未找到我的确切解决方案。下面是我的示例代码

    NSMutableDictionary *callDict =[[NSMutableDictionary alloc] init];
    [callDict setObject:@"messages-getModuleMessages" forKey:@"call"];
    [callDict setObject:FB_API_KEY forKey:@"accessSecret"];
    NSString *x=[FBUserManager sharedUserManager].authToken;
    [callDict setObject:x forKey:@"authToken"];
       [callDict setObject:@"json" forKey:@"format"];

    [callDict setObject:@"inbox" forKey:@"callType"];


    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.fretbay.com/fr/private/api/rest-server.php?",calldict]];//here recieving warning

    [request setHTTPMethod:@"GET"];

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

    NSError *err;
    NSURLResponse *response;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];     // here parsing the array

3 个答案:

答案 0 :(得分:4)

    NSDictionary *parameters = @{
        @"call": @"messages-getModuleMessages",
        @"accessSecret": FB_API_KEY,
        @"authToken": [FBUserManager sharedUserManager].authToken,
        @"format": @"json",
        @"inbox":@"callType"
    };

    NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.fretbay.com/fr/private/api/rest-server.php?"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
            fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json);
    }];

    [dataTask resume];

答案 1 :(得分:2)

假设这些是您的strings

NSString *messages-getModuleMessages=@"messages-getModuleMessages";
NSString * authtincateToken=@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =@"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =@"hai thios is textmessage";

// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,@"call",authtincateToken,@"authToken", accessSecretkey, @"accessSecret",inboxvalue,@"calotype",@"json",@"format",nil];

  // convert your dictionary to NSData
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
 // this is your service request url
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];
 // set the content as format
 [request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
  // this is your response type        
 [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
   NSError *err;
  NSURLResponse *response;
   // send the synchronous connection
   NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
   // here add your server response NSJSONSerialization
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; 

  // if u want to check the data in console
  NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", tmp);

答案 2 :(得分:0)

将以下方法添加到Call WebService

- (void) callWebservice_Block : (NSDictionary *) jsonDict :(void(^)(NSDictionary * dic, NSError * err))responseHandler{

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&err];
NSString * jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];;

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"Past your URL Here"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];


[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        responseHandler (nil,error);

    } else {
        NSDictionary * returnDict  = [NSJSONSerialization JSONObjectWithData:data
                                                                 options: NSJSONReadingMutableContainers
                                                                   error: &error];
        responseHandler (returnDict,nil);
    }

    }];} 

您可以通过以下方式Call Method

NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:@"FirstValue",@"FirstKey",@"SecondValue",@"SecondKey", nil];

[self callWebservice_Block:jsonDict :^(NSDictionary *dic, NSError *err) {
    if(!err){
        NSLog(@"Got Response :- %@",dic);
    }

}];