2014-09-29 89 views
2

这是JSON字符串,我要张贴...我如何可以张贴的JSON字符串到服务器

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

如何发布的JSON?

回答

3

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

首先成立了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); 

其次,正确地异步发送命令和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 

最后,(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"]; 
     }]; 

    } 

希望它可以节省一些人打字!

+0

谢谢,吹你不知道我是如何填补,但我现在好了。 – 2014-09-29 07:55:05

+0

是的,它帮助我..再次感谢 – 2014-09-29 08:44:14

+0

你是男人乔Blow ....我一直在寻找这个代码几个月,我没有收到任何解决方案...现在我明白了!谢天谢地,上帝保佑! – 2015-09-04 17:22:43

0

使用以下shnchronous请求,可以使用异步请求,以及,

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 
0

替换:

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

随着:

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

一个对象,它可被转换为JSON必须具有以下属性:

  • 顶层对象是NSArray或NSDictionary。
  • 所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例。
  • 所有的字典键都是NSString的实例。
  • 数字不是NaN或无穷大。
+0

嗨,丹 - 错误-Terminating应用程序由于未捕获的异常 'NSInvalidArgumentException',理由是: '*** + [NSJSONSerialization dataWithJSONObject:选项:错误:]:在JSON写无效的顶层类型' – 2014-09-29 07:35:29

+0

我已编辑我的帖子。检查你的代码是否遵循规则 – 2014-09-29 08:21:28

0
  • 按我的观点,你可以使用NSURLSeession与ASYN请求(尝试实施NSURLSession)

的NSData * POSTDATA = [NSJSONSerialization dataWithJSONObject:数据选项:0错误:&错误]

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:)]; 
}