2013-06-04 111 views
0

試圖從json中獲取值,顯示正確獲取數據的響應字符串,但是當NSData轉換並將其放入NSDictionary中時,兩個值會互換。 下面是代碼嘗試。從JSON獲取NSData的奇怪響應

+(NSMutableDictionary *)seatMap:(NSDictionary *)seatId eventId:(NSDictionary *)eid 
{ 
NSString *urlStr = [NSString stringWithFormat:@"http://met.co/api/seatmap/%@/%@", [seatId valueForKey:@"sid"], [eid valueForKey:@"eid"]]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: 
           [NSURL URLWithString: 
           [urlStr stringByAddingPercentEscapesUsingEncoding: 
            NSUTF8StringEncoding]]]; 
//NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlStr]]; 

NSString *responseString = [MetApi sendRequest:request]; 
NSLog(@"response:%@", responseString); 
NSError *error; 
NSData *jsonData = [responseString dataUsingEncoding:NSUTF16StringEncoding]; 
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 

//NSDictionary *results = [responseString JSONValue]; 
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:results]; 
NSLog(@"dict in API-------------%@",dict); 

return dict; 
} 

以上代碼給這個輸出

 1 = off; 
     10 = off; 
     2 = on; 
     3 = on; 
     4 = on; 
     5 = on; 
     6 = on; 
     7 = on; 
     8 = on; 
     9 = on; 

但應該

1: "off", 
2: "on", 
3: "on", 
4: "on", 
5: "on", 
6: "on", 
7: "on", 
8: "on", 
9: "on", 
10: "off" 

JSON文件

{ 
row1: { 
1: "on", 
2: "on", 
3: "on", 
4: "on", 
5: "on", 
6: "on", 
7: "on", 
8: "on", 
9: "on", 
10: "on", 
attr: { 
total: "10", 
type: "Gold" 
} 
}, 
row2: { 
1: "off", 
2: "on", 
3: "on", 
4: "on", 
5: "on", 
6: "on", 
7: "on", 
8: "on", 
9: "on", 
10: "off", 
attr: { 
total: "10", 
type: "Gold" 
} 
} 
} 
} 

爲什麼這個交換數據的情況發生。請指導以上內容,如有不清楚的地方請提問。 在此先感謝。

+0

得到某種答案這裏的NSDictionary objectForKey:方法的價值。 [1]:http://stackoverflow.com/questions/16913847/sort-nsdictionary-in-ascending-order/16915518?noredirect=1#16915518 –

回答

3

您的JSON只包含字典和字典不維護順序。換句話說,打印字典時元素的順序完全是特定於實現的,甚至可能是隨機的。

如果順序是相關的,你必須使用列表(例如[1,2,3]

例如,你可以使用下面的JSON

{ "rows": 
    [ { "values":["on", "on", "on", "on", "on", "on", "on", "on", "on", "on"] 
    , "attr": { "total": 10 
       , "type": "Gold" 
       } 
    } 
, { "values":["off", "on", "on", "on", "on", "on", "on", "on", "on", "off"] 
    , "attr": { "total": 10 
       , "type": "Gold" 
       } 
    } 
    ] 
} 

如果你不想改變你的JSON,並得到值,以便您可以使用下面的代碼片段說的row1(不推薦,如果順序很重要,請使用清單!):

/* expects `NSDictionary *dict` as defined in the code of your question. Code is untested but should give you the idea... */ 
NSInteger max = [dict[@"row1"][@"attr"][@"total"] intValue]; 

for (int i=1; i<= max; i++) { 
    NSLog("value %ld = '%@'", i, dict[@"row1"][@"attr"][[NSString stringWithFormat:@"%d",i]]); 
} 
+0

我沒有明白你的意思。 –

+0

好的,但沒有任何解決方案編程,我可以處理形式我的代碼。 –

+0

什麼問題?我猜想問題是,訂單是「1,10,2,3,4,5,6,7,8,9」而不是「1,2,3,4,5,6,7,8,9 ,10「 –

0

NSDictionary鍵值對重要不是它在appearence

爲了你可以使用,即使爲了改變