2014-02-11 26 views
0

在我的iPhone应用程序,我想给我的数据在JSON format.I在储存了所有的数据在dictionary.How改变JSON格式的词典数据,然后用它发送到服务post方法(我只需要发送到服务器)。如何发布JSON数据到服务器

+0

您是否在项目中导入了JSON类文件? – NiravPatel

+0

我试过这段代码:-NSDictionary * jsonDict = [NSDictionary dictionaryWithObject:AnswerData forKey:@“question”]; 的NSData * jsonData = [NSJSONSerialization dataWithJSONObject:AnswerData选项:NSJSONWritingPrettyPrinted错误:错误];但在不defined.such错误“错误”我是gettig .. – user3247436

+0

如果您正在使用JSON类文件,那么这将是很容易转换你的字典转换成JSON。 – NiravPatel

回答

0

如果您使用SBJSON然后用下面的代码,你可以创建的NSDictionary JSON字符串。

SBJsonWriter *jsonWriter = [SBJsonWriter new]; 
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys]; 
NSString *jsonString = [jsonWriter stringWithObject:dict]; 
0

尝试

NSMutableDictionary *Dict=[[NSMutableDictionary alloc] initWithObjectsAndKeys:str,@"str",str1,@"str1",Idstr,@"Idstr",nil]; 
    NSError *error=nil; 
    NSData *Data=[NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error]; 
    NSMutableString *JsonString = [[NSMutableString alloc] initWithData:Data encoding:NSUTF8StringEncoding]; 



    NSMutableString *[email protected]"url" 
    NSURL *url=[NSURL URLWithString:urlstr]; 
    NSMutableURLRequest *urlrequest=[NSMutableURLRequest requestWithURL:url]; 


    NSString *urlbody=[NSString stringWithFormat:@"inputParam=%@",JsonString]; 
    [urlrequest setHTTPBody:[Alerturlbody dataUsingEncoding:NSUTF8StringEncoding]]; 
    [urlrequest setHTTPMethod:@"POST"]; 
    [urlrequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Accept"]; 
    [urlrequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [urlrequest setValue:[NSString stringWithFormat:@"%d", [urlbody length]] forHTTPHeaderField:@"Content-Length"]; 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
    [NSURLConnection sendAsynchronousRequest:urlrequest queue:queue completionHandler:^(NSURLResponse *response, NSData *Resdata, NSError *error) 
    { 



      NSError* error; 
      NSDictionary *jsondict = [NSJSONSerialization 
             JSONObjectWithData:Resdata //1 
             options:kNilOptions 
             error:&error]; 
       //NSLog(@"jsondict:%@",jsondict); 




     } 
     else if ([Resdata length] == 0 && error == nil) 
     { 
      NSLog(@"Nothing was downloaded."); 

     else if (error != nil) 
     { 
      NSLog(@"Error happened = %@", error); 



     } 
    }];