2014-02-11 28 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); 



     } 
    }];