可能重复:
JSONkit sorting issues
我有以下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
答案 0 :(得分:2)
使用标准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
}
}
答案 1 :(得分:1)
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说,你应该为每个JSON Entry使用Arrays。
但你也可以尝试使用smth:
[
[
"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,...},
]
]
答案 2 :(得分:0)
字典没有订购商品。排序由iOS完成,以便很好地显示它。但是,您不应该假设字典中的任何项目顺序。