Post Request in Json format iOS

别来无恙 提交于 2019-12-13 00:47:30

问题


I am new in iOS i have to send post request in json format. like,

  {"user":{"email":"abc@gmail.com"}}

My coding is like,

NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:@"test@gmail.com" forKey:@"email"];
//  [postDict setValue:text_password.text forKey:@"password"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
NSString *stringData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

I am getting output

  {"email":"test@gmail.com"}

Please let me know how to add {"user":

Thank you.


回答1:


make One more Dictionary and pass first one dictionary into second you got your format

NSMutableDictionary *firstDic=[[NSMutableDictionary alloc]init];
[data setValue:@"abc@gmail.com" forKey:@"email"]; NSMutableDictionary
*secondDic=[[NSMutableDictionary alloc]init];    
[userInfo setValue:firstDic forKey:@"user"];

Hope this is helpfull




回答2:


If you want - {"user":{"email":"abc@gmail.com"}}

Then You need two dictionaries for this.

First one for the inner dictionary - {"email" : "abc@gmail.com"}. And

Second one for the outer dictionary - {"user" :{....}}

So first Create the inner dictionary.Such as-

NSMutableDictionary *data=[[NSMutableDictionary alloc]init];
[data setValue:@"abc@gmail.com" forKey:@"email"];

Now create the outer dictionary.Such as-

NSMutableDictionary *userInfo=[[NSMutableDictionary alloc]init];   
[userInfo setValue:data forKey:@"user"];

And now create the JSON object-

NSData *JSONData=[[NSData alloc] init];
if([NSJSONSerialization isValidJSONObject:userInfo])
{
    JSONData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:nil];
}
NSString *jsonString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString); 

And the output will be- {"user":{"email":"abc@gmail.com"}}

Hope it will help you.




回答3:


1) Post Data Using Default Function :-

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setValue:@"test@gmail.com" forKey:@"email"];


        NSString *post =[dict JSONRepresentation];

        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        //NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%ld",(long)[postData length]];

        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

        [request setURL:[NSURL URLWithString:[NSString stringWithFormat:”YourURL”]]];

      //  [request setTimeoutInterval:30.0f];

        [request setHTTPMethod:@"POST"];

        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

        [request setHTTPBody:postData];

        NSURLConnection * connection = [[NSURLConnection alloc]
                                        initWithRequest:request
                                        delegate:self startImmediately:NO];

2) Post Data Using AFNetworking Library :-

  NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:@"test@gmail.com" forKey:@"email"];


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@“Your URL”]]];
    [request setHTTPMethod:@"POST"];

    NSString *post =[dict JSONRepresentation];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%ld",(long)[postData length]];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];

    //Add your request object to an AFHTTPRequestOperation
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {

         NSString *response = [operation responseString];
         NSLog(@"response: %@",response);

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error: %@", [operation error]);
     }];

    //call start on your request operation
    [operation start];



回答4:


I would suggest to enhance your mind to more dynamic way, because its very easy to do, but for your question, you can achieve it by code like this,

NSMutableDictionary *postDict =[[NSMutableDictionary alloc] init];
NSMutableDictionary *dicEmail =[[NSMutableDictionary alloc] init];
[dicEmail setObject:@"abc@gmail.com" forKey:@"email"];
[postDict setObject:dicEmail forKey:@"user"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
NSString *stringData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Enjoy Coding!!



来源:https://stackoverflow.com/questions/29887641/post-request-in-json-format-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!