2012-10-10 50 views
2

我想要做的是取一個JSON提要,然後遍歷結果。但是,當我從字典中獲取對象時,我總是得到一個字符串而不是數組。關於我在做什麼的任何想法都是錯誤的?Objective C解析JSON,字典返回一個NSCFString而不是NSArray

這裏的JSON:

[ 
    { 
    "_id": "4f6d9a7c1d0b4900010007ee", 
    "geo_triggers": [ 
     { 
     "_id": "4fc3e5fdc7234e0001000002", 
     "location": [1,1], 
     "longitude": "1", 
     "latitude": "1", 
     "radius": 1, 
     "location_name": "Test 1" 
     }, 
     { 
     "_id": "4fc61f3762f53f0001000043", 
     "location": [-71.057673,42.355395], 
     "longitude": "-71.057673", 
     "latitude": "42.355395", 
     "radius": 1000, 
     "location_name": "Test2" 
     } 
    ] 
    } 
] 

這裏的目標C代碼:

const char* className = class_getName([result class]); 
NSLog(@"Result is a: %s", className); 
NSLog(@"%@", result); //string 
NSArray* json = [result objectForKey:@"result"]; //should be an array of dictionaries 
NSLog(@"JSON Output: %@", json); 
const char* className1 = class_getName([json class]); 
NSLog(@"yourObject is a: %s", className1); 

而這裏的輸出:

Result is a: __NSDictionaryI 
2012-10-10 17:15:15.165 App[12980:19d03] { 
    result = "[{\"_id\":\"4f6d9a7c1d0b4900010007ee\",\"geo_triggers\":[{\"_id\":\"4fc3e5fdc7234e0001000002\",\"location\":[1.0,1.0],\"longitude\":\"1\",\"latitude\":\"1\",\"radius\":1,\"location_name\":\"Test 1\"},{\"_id\":\"4fc61f3762f53f0001000043\",\"location\":[-71.057673,42.355395],\"longitude\":\"-71.057673\",\"latitude\":\"42.355395\",\"radius\":1000,\"location_name\":\"Test2\"}]}]"; 
} 
2012-10-10 17:15:15.166 App[12980:19d03] JSON Output: [{"_id":"4f6d9a7c1d0b4900010007ee","geo_triggers":[{"_id":"4fc3e5fdc7234e0001000002","location":[1.0,1.0],"longitude":"1","latitude":"1","radius":1,"location_name":"Test 1"},{"_id":"4fc61f3762f53f0001000043","location":[-71.057673,42.355395],"longitude":"-71.057673","latitude":"42.355395","radius":1000,"location_name":"Test2"}]}] 
2012-10-10 17:15:15.166 App[12980:19d03] yourObject is a: __NSCFString 
2012-10-10 17:15:15.166 App[12980:19d03] -[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb331800 

回答

5

result變量指向的字典。該字典包含一個鍵。那個關鍵是@"result"。該密鑰的值是一個字符串,@"[{\"_id\":\"4f6d9a7c1d0b4900010...

換句話說,你還沒有真正反序列化你的JSON。您需要獲取密鑰result的值並通過JSON解串器運行。

+0

謝謝 - 這使得更有意義。得到它的工作! –

1

首先需要解碼結果。以上是JSON所以我建議這樣做

  1. 如果您還沒有將其下載JSONKit.h,包括在您的項目
  2. 然後你就可以做

    1. NSString* json = [result JSONString];看到輸出
    2. 東西像id jsonDict = [[JSONDecoder decoder] objectWithData:responseData]; 之後,你可以做[jsonDict objectForKey:@「_ id」]; ///等
相關問題