0

试图从 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"
}
}
}
}

为什么会发生这种数据交换。以上请指教,如有不明白请追问。提前致谢。

4

2 回答 2

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]]);
}
于 2013-06-04T05:10:37.487 回答
0

In NSDictionary key value pairs matters not its order in appearence

You can get the value using objectForKey: method even if the order is changed

于 2013-06-04T05:21:51.237 回答