![](/img/trans.png)
[英]why Json Dictionary is Giving the response in nsdata(Bytes) always.How can i Get the Dictionary from web service
[英]Strange response from NSData fetching from JSON
嘗試從json提取值,響應字符串顯示正確的提取數據,但是當NSData轉換並將其放入NSDictionary時,兩個值會互換。 下面是嘗試的代碼。
+(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"
}
}
}
}
為什么發生這種數據交換。 請為上述內容提供指導,如果不清楚,請詢問。 提前致謝。
您的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]]);
}
在NSDictionary
鍵值對的出現與其順序無關緊要
即使更改了順序,也可以使用objectForKey:
方法獲取值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.