2014-12-04 82 views
0

如何將NSDictionary轉換爲JSON?將NSDictionary轉換爲JSON

我已經發布了一個字典到服務器使用JSON。並且在使用GET方法從服務器接收數據的時間。數據不能用正常的密鑰調用方法訪問,如

_secretanswer.text=[[NSString alloc]initWithFormat:@"%@",[customfield objectForKey:@"secanswer"]]; 

服務器返回一個NCFString作爲結果。

如何轉換和發佈JSON格式的NSDictionary?

+1

JSON或賈森? – Dev 2014-12-04 12:13:59

+2

誰是_JASON?_ – holex 2014-12-04 12:36:29

回答

0
NSError * error; 
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&error]; 

NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]  
+0

看來很清楚OP是從他的JSON數據顯式尋找NSDictionary,而不是NSString。 – geraldWilliam 2015-04-08 19:05:14

0

我相信你要找的是NSJSONSerialization。

這個答案假定使用NSURLConnection的基於塊的API來執行你的GET。

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
    if (data) { 
     NSError *jsonError = nil; 
     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; 
     if (dict) { 
      // You got a valid NSDictionary out of your JSON response. 
      NSLog(@"my returned dictionary: %@", dict); 
     } else if (jsonError) { 
      // JSON data could not be parsed into NSDictionary. Handle as appropriate for your application. 
      return; 
     } 
    } else if (connectionError) { 
     // Handle connection error 
    } 
}]; 

但即使您使用的是dataWithContentsOfURL :,點也是一樣的。將您的數據輸入到NSJSONSerialization的+ jsonObjectWithData:options:error:方法中,檢查是否從中得到了字典,然後繼續。

編輯:如果您正在爲NSDictionary的HTTP請求創建JSON發佈主體,那麼NSJSONSerialization也包含在其中。

NSError *error = nil; 
NSData *data = [NSJSONSerialization dataWithJSONObject:someDictionary options:NSJSONWritingPrettyPrinted error:&error]; 
if (data) { 
    // You got your data. 
    NSLog(@"my data: %@", data); 
    [someURLRequest setHTTPBody:data]; 
} else if (error) { 
    NSLog(@"error: %@", [error localizedDescription]); 
} 
+1

Downvoted不包括錯誤處理。 – 2015-04-08 13:07:21

+0

@HotLicks謝謝你。答案已更新。 – geraldWilliam 2015-04-08 18:54:14

+0

您在添加的錯誤處理中犯了一個常見的錯誤。請參閱https://www.bignerdranch.com/blog/an-nserror-error/ https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html#//apple_ref/doc/uid/TP40011210-CH9-SW5 – 2015-06-17 22:06:39