可能重复:
我有下面的jSON
[
{
"Pending": 67,
"Past Due": 63,
"Invites": 0
},
{
"Reading Approval": 4,
"Schedule Approval": 16,
"Session Assignment": 1
},
{
"Reading Approval": 3,
"Schedule Approval": 20,
"Class Approval": 20,
"Module Approval": 2,
"Training Plan Review": 2,
"Job Confirmation": 1
}]
当我将json字符串分配给nsarray时,字典中的值会按字母顺序排序。
NSArray *arr = [strResult JSONValue]; 如何保持与json字符串相同的顺序?
arr =
{
Invites = 0;
"Past Due" = 63;
Pending = 67;
},
{
"Reading Approval" = 4;
"Schedule Approval" = 16;
"Session Assignment" = 1;
},
{
"Class Approval" = 20;
"Job Confirmation" = 1;
"Module Approval" = 2;
"Reading Approval" = 3;
"Schedule Approval" = 20;
"Training Plan Review" = 2;
}
)这是我想显示的表:
Group 1
Pending 67
Past Due 63
Invites 0
Group 2
Reading Approval 4
Schedule Approval 16
Session Assignment 1
Group 3
Reading Approval 3
Schedule Approval 20
Class Approval 20
Module Approval 2
Training Plan Review 2
Job Confirmation 1发布于 2012-05-29 14:33:07
使用标准的JSON解析器,您将需要更改数据。
[
[
{ "Pending": 67 },
{ "Past Due": 63 },
{ "Invites": 0 }
],
[
{ "Reading Approval": 4 },
{ "Schedule Approval": 16 },
{ "Session Assignment": 1 }
],
[
{ "Reading Approval": 3 },
{ "Schedule Approval": 20 },
{ "Class Approval": 20 },
{ "Module Approval": 2 },
{ "Training Plan Review": 2 },
{ "Job Confirmation": 1 }
]
]假设您可以更改JSON格式。
如何访问数据。假设您有一个节数组,并且知道节和行索引。
NSArray *sections = ...
NSUInteger sectionIndex = ...
NSUInteger rowIndex = ...
NSArray *rows = [sections objectAtIndex:sectionIndex];
NSDictionary *cell = [rows objectAtIndex:rowIndex];
NSString *name = [[cell allKeys] objectAtIndex:0];
NSNumber *value = [cell objectForKey:name];
// What ever you need to do如果您想迭代所有的数据
NSArray *sections = ...
for (NSArray *rows in sections) {
for (NSDictionary *cell in rows) {
NSString *name = [[cell allKeys] objectAtIndex:0];
NSNumber *value = [cell objectForKey:name];
// What ever you need to do
}
}发布于 2012-05-29 15:21:43
NSDictionary是无序容器对象。如果它被打印出来,它将按字母顺序排序。但是没有保证的秩序。
description:的文档显示:
If each key in the dictionary is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. [...]allKeys:说:
The order of the elements in the array is not defined.allValues还说:
The order of the elements in the array is not defined.但是NSArray是一个命令的容器。这就是Jeffery Thomas statet的原因,您应该为每个JSON条目使用数组。
但你也可以试着用这样的气味:
[
[
"keys": {"Pending","Past Due","Invites"},
"values": {67,63,0}
],
[
"keys": {"Reading Approval","Schedule Approval","Session Assignment"},
"values": {4,16,1},
],
[
"keys": {"Reading Approval","Schedule Approval","Class Approval",...},
"values": {3,20,20,...},
]
]发布于 2012-05-29 15:14:09
字典中的项目没有排序。排序是由iOS完成的,只是为了很好地显示它。但是,您不应该假设字典中的项目排序。
https://stackoverflow.com/questions/10800285
复制相似问题