2012-08-03 31 views
3

我是iOS新手。如何從NSData獲取信息?

的NSData:

{ 
"results" : [ 
    { 
    "formatted_address" : "Proyezd Voskresenskiye Vorota, 3, Moscow, Russia, 109012", 
    "geometry" : { 
     "location" : { 
      "lat" : 55.75622380, 
      "lng" : 37.61855850 
     } 

我只需要 「的formatted_address」,你能不能幫我做一個的NSString中,這將是地址? 對不起,愚蠢的問題。

+2

你從哪裏得到的數據?你有沒有試過NSKeyedArchiver/Unarchiver? – 2012-08-03 15:09:30

+0

[[foo objectForKey:@「results」] objectAtIndex:0] objectForKey:@「formatted_address」];字典對象,獲取對象關鍵的「結果」,它看起來像一個數組,從該數組中獲取第一個對象(objectAtIndex:0)..這是一個字典.. get objectForKey formatted_address – 0x8badf00d 2012-08-03 15:18:36

回答

6

您的NSData是JSON響應,您需要創建一個NSDictionary才能訪問數據的特定部分。一個NSDictionary只是將鍵映射到值。要獲得值,請致電– objectForKey:。在你的情況下,你有一個字典作爲關鍵「結果」的值。所以在你的情況下:

NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
NSDictionary *resultsDictionary = [[results objectForKey:@"results"] objectAtIndex:0]; 
NSString *formattedAddress = [resultsDictionary objectForKey:@"formatted_address"]; 
+0

非常感謝! – quaddef 2012-08-03 17:11:16

1

看看NSJSONSerialization類。還有就是你的數據轉換成詞典的方法:

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; 

有了這一點,你應該可以問你的新創建的NSDictionary檢索您的NSString。