簡體   English   中英

如何在JSON中將字典作為參數傳遞

[英]How to pass dictionary as a parameter in JSON

我是json的新手,我想將dictionary作為參數與url一起傳遞給服務器,如何在方法發布時完成它? 我嘗試過示例代碼,但沒有找到確切的解決方案。以下是我的示例代碼

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

假設這些是你的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);

將以下方法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);
    }

}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM