繁体   English   中英

来自JSON的NSData提取的奇怪响应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM