2014-02-10 45 views
0

1.I從Web服務得到JSON數據,並將其添加對NSDictionary中GET值不起作用

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; 

2.然後我秀 「DIC」 中的NSLog這是目前

{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]} 

3 。然後我在新的NSDictionary「DIC」獲取數據值「DT」

NSDictionary *dt = [dic objectForKey: @"query"]; 

4.然後我的NSLog顯示「DT」這是目前

({ID = 01;IndexNo = 1;Picture = "img/food-48.png";}) 

5.我想從「dt」中獲得「ID」。我用這個代碼

NSString *ID = [dt objectForKey: @"ID"]; 

,但你可以試試這個

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; 
NSArray *arr = [dic objectForKey: @"query"]; 
NSDictionary *dt = arr[0]; 
NSString *ID = [dt objectForKey: @"ID"]; 
+0

是ID的值是否是NSString對象? – LML

回答

1

。注意,這些方括號從第一的NSLog語句的輸出:

{"query": [...]} 

試試這個:

NSArray *dtArray = [dic objectForKey: @"query"]; 
NSDictionary *dt = dtArray[0]; 
NSString *ID = [dt objectForKey:@"ID"]; 

或者使用NSDictionary中的和鍵 - 值編碼行爲NSArray

NSString *ID = [[dic valueForKeyPath:@"query.ID"] firstObject]; 
0

[dic objectForKey: @"query"]實際上返回一個NSArray它的錯誤

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8a40a60 
0
NSDictionary *dt = [[dic objectForKey: @"query"] objectAtIndex:0]; 
NSString *ID = [dt objectForKey: @"ID"]; 

您正試圖從數組中獲取鍵的值。改變這些線。

0

從你jsonStructure

{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]} 

對象鍵「查詢」是一個數組爲{}是一個字典和[]是一個數組。

NSArray *tempArray = [dt objectForKey:@"query"]; 

    NSDictionary *tempDictionary = [tempArray objectAtIndex:0]; 
    NSString *ID = [tempDictionary objectForKey:@"ID"]; 

希望這會有所幫助。