如何在 NSDictionary Objective c 中对 Json 值进行排序?



我想按location_name对嵌套的 Json 数组进行排序,我的 json 在 nsdictionary 中

JSON 数组是

apiResult:{
Description = "List of Location";
code = 200;
locationList =     (
{
"location_id" = 481;
"location_name" = "<null>";
"pre_fixied" = "$3.00";
"state_name" = Melbourne;
status = 0;
zone = "Zone 2";
"zone_id" = 30;
},
{
"location_id" = 461;
"location_name" = "O'Halloran Hill";
"pre_fixied" = "$5.00";
"state_name" = Adelaide;
status = 1;
zone = "Zone 3";
"zone_id" = 31;
},
{
"location_id" = 460;
"location_name" = "Sheidow Park";
"pre_fixied" = "$5.00";
"state_name" = Adelaide;
status = 1;
zone = "Zone 3";
"zone_id" = 31;
},
{
"location_id" = 459;
"location_name" = "Hallett Cove";
"pre_fixied" = "$5.00";
"state_name" = Adelaide;
status = 1;
zone = "Zone 3";
"zone_id" = 31;
},
{
"location_id" = 458;
"location_name" = "Eden Hills";
"pre_fixied" = "$5.00";
"state_name" = Adelaide;
status = 1;
zone = "Zone 3";
"zone_id" = 31;
},
{
"location_id" = 457;
"location_name" = Glengowrie;
"pre_fixied" = "$5.00";
"state_name" = Adelaide;
status = 1;
zone = "Zone 3";
"zone_id" = 31;
}
);
message = "List of Location";
status = Success;
} 

它按位置 ID 降序显示,我希望这个 JSON 按位置名称升序排列。 我有单独的排序位置列表数组,但我想要整个json和位置列表按位置名称顺序排列

试试这个

locationDescriptor = [[NSSortDescriptor alloc] initWithKey:@"location_id" ascending:YES];
sortDescriptors = [NSArray arrayWithObject: locationDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

现在根据需要将sortedArray更改为任何其他格式。

第一个简短的位置数组。

假设您的 JSON 结果是NSDictionary *jsonResult;并且过滤后的数组是NSArray *filteredArray;

然后

NSMutableDictionary *filteredJson = [NSMutableDictionary new];
[filteredJson setObject:[jsonResult valueForKey:@"Description"] forKey:@"Description"];
[filteredJson setObject:[jsonResult valueForKey:@"code"] forKey:@"code"];
[filteredJson setObject:filteredArray forKey:@"locationList"];
[filteredJson setObject:[jsonResult valueForKey:@"message"] forKey:@"message"];
[filteredJson setObject:[jsonResult valueForKey:@"status"] forKey:@"status"];

最新更新