尝试从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"
}
}
}
}
为什么这种数据交换正在发生。请指导以上,如果有什么不清楚请询问。 提前谢谢。
答案 0 :(得分: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]]);
}
答案 1 :(得分:0)
在NSDictionary
关键值对事项不是它的外观顺序
即使订单已更改,您也可以使用objectForKey:
方法获取值