【发布时间】:2014-02-23 19:35:02
【问题描述】:
常见任务,将字符串转换为 JSON 格式。是的,很简单,StackOverflow 上有很多关于这个的答案。
对我来说不太容易理解的是为什么我得到的顺序与我将 pair 对象放入 NSDictionary 中的顺序不同。
这是我写的代码:
-(NSString*)createJSONstring
{
//http://www.raywenderlich.com/5492/working-with-json-in-ios-5
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"<xx3-xxxx>",@"from",
@"<xxx-xxx>",@"to",
@"<Bla bla bla>",@"message",
@"<2000>",@"posixtime", nil];
NSArray* notifications = [NSArray arrayWithObjects:dictionary, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString);
return jsonString;
}
我希望得到这样的东西:
{
"from" : "<xx3-xxxx>"
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"posixtime" : "<2000>",
}
但我得到了不同的顺序:
{
"posixtime" : "<2000>", <----- INCORRECT
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"from" : "<xx3-xxxx>" <----- INCORRECT
}
如何以与插入数组相同的顺序获取输出?
[NSDictionary dictionaryWithObjectsAndKeys: //I want it to be:
@"<xx3-xxxx>",@"from", //1st
@"<xxx-xxx>",@"to", //2nd
@"<Bla bla bla>",@"message", //3rd
@"<2000>",@"posixtime", nil]; //4th
【问题讨论】:
-
通常使用字典,顺序无关紧要,因为您将通过键访问值。您能否扩展需要键项的顺序一致的用例?
-
不保证保留 JSON“对象”中键/值对的顺序。
-
来自 json.org:“一个对象是一组 无序 名称/值对。”
标签: ios objective-c json nsdictionary nsdata