xcode 我如何将 json 字符串发布到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26094270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:43:58  来源:igfitidea点击:

How can i post json string to server

iosobjective-ciphonejsonxcode

提问by Amit Kumar

This is json string that I have to post...

这是我必须发布的json字符串...

{
    "data": {
        "description": "",
        "current_value": "",
        "serialno": "",
        "condition": "",
        "category": "category",
        "purchase_value": "",
        "new_or_used": "",
        "gift_or_purchase": "",
        "image": ""
    },
    "subtype": "fd3102d8-bc19-424b-bca2-774a8fd7ea6f"
}

How to post as JSON?

如何发布为 JSON?

回答by Fattie

Surely this Q us a duplicate, but here's full example code, as one long routine. Just copy and paste.

当然,这个 Q 我们是重复的,但这里有完整的示例代码,作为一个长例程。只需复制和粘贴。

First set up the JSON...

首先设置JSON...

-(void)sendTestJsonCommand
    {
    NSMutableDictionary *dict = @{
        @"heights":@"4_5_7",
        @"score":@"4",
        @"title":@"Some Title",
        @"textBody":@"Some Long Text",
        @"happy":@"y"
        }.mutableCopy;

    NSError *serr;

    NSData *jsonData = [NSJSONSerialization
        dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&serr];

    if (serr)
        {
        NSLog(@"Error generating json data for send dictionary...");
        NSLog(@"Error (%@), error: %@", dict, serr);
        return;
        }

    NSLog(@"Successfully generated JSON for send dictionary");
    NSLog(@"now sending this dictionary...\n%@\n\n\n", dict);

Next, correctly asynchronously send the command and json to your server...

接下来,正确地将命令和 json 异步发送到您的服务器...

#define appService [NSURL \
  URLWithString:@"http://www.corp.com/apps/function/user/pass/id/etc"]

    // Create request object
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:appService];

    // Set method, body & content-type
    request.HTTPMethod = @"POST";
    request.HTTPBody = jsonData;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setValue:
        [NSString stringWithFormat:@"%lu",
        (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];

    // you would almost certainly use MBProgressHUD at this point
    // to display some sort of spinner or similar action on the UX

Finally, (A) connect correctly using NSURLConnection, and (B) correctly interpret the information which comes back to you from your server.

最后,(A) 使用 NSURLConnection 正确连接,以及 (B) 正确解释从您的服务器返回给您的信息。

    [NSURLConnection sendAsynchronousRequest:request
        queue:[NSOperationQueue mainQueue]
        completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)
        {

        if (!data)
            {
            NSLog(@"No data returned from server, error ocurred: %@", error);
            NSString *userErrorText = [NSString stringWithFormat:
               @"Error communicating with server: %@", error.localizedDescription]
            return;
            }

        NSLog(@"got the NSData fine. here it is...\n%@\n", data);
        NSLog(@"next step, deserialising");

        NSError *deserr;
        NSDictionary *responseDict = [NSJSONSerialization
                                      JSONObjectWithData:data
                                      options:kNilOptions
                                      error:&deserr];

        NSLog(@"so, here's the responseDict\n\n\n%@\n\n\n", responseDict);

        // LOOK at that output on your console to learn how to parse it.
        // to get individual values example blah = responseDict[@"fieldName"];
        }];

    }

Hope it saves someone some typing!

希望它可以为某人节省一些打字时间!

回答by Parth Pandya

Use following shnchronous request, you can use asynchronous request as well,

使用以下同步请求,您也可以使用异步请求,

NSError *error;

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:<Your API URL>]];

  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:<Your Mutable NSDictionary> options:NSJSONReadingMutableContainers error:&error];


 [request setHTTPMethod:@"POST"];
 [request setHTTPBody:jsonData];

  NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  //NSLog(@"results string = %@",[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]);


 NSDictionary *temp= [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];// This will convert Data to Json format

回答by dmerlea

Replace:

代替:

NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

With:

和:

NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:&error];

An object that may be converted to JSON must have the following properties:

可以转换为 JSON 的对象必须具有以下属性:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.
  • 顶级对象是 NSArray 或 NSDictionary。
  • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
  • 所有字典键都是 NSString 的实例。
  • 数字不是 NaN 或无穷大。

回答by Pallavi Ligade

  • As per my point of view you can Use NSURLSeession with Asyn request (Try to implement NSURLSession)
  • 根据我的观点,您可以将 NSURLSeession 与 Asyn 请求一起使用(尝试实现 NSURLSession)

NSData *postData =[NSJSONSerialization dataWithJSONObject:Data options:0 error:&error];

NSData *postData =[NSJSONSerialization dataWithJSONObject:Data options:0 error:&error];

if (!error)
{
    NSString *urlpart = [NSString stringWithFormat:@“Your URL];
    NSURL *requestUrl = [NSURL URLWithString:urlpart];
    NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    URLRequest.allowsCellularAccess=YES;
    [URLRequest setHTTPMethod:@"POST"];
    [URLRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [URLRequest setHTTPBody:postData];
    WebServiceManager *webserviceManager = [[WebServiceManager alloc] init];// this is your comman class for webServices connections 
    [webserviceManager sendRequest:URLRequest withOwner:self successAction:@selector(delegateMethod:) failAction:@selector(Error:)];
}