JSON数组和排序 [英] JSON Arrays and Sorting

查看:154
本文介绍了JSON数组和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面概述的这个json数组.我想知道如何仅将所有字符串放在名称"键下,并放置在某个数组中,然后按名称按字母顺序排序,然后根据名称中的第一个字母将其拆分为其他数组.非常感谢任何执行此操作的指南.我正在通过github和NSJSONserialization使用json工具包.

I have this json array which I have outlined below. I want to know how I could get all the strings under the "name" key only and place in a certain array to be sorted alphabetically by name and later split into further arrays in accordance to the first letter in the names. Any guide to carrying this out will be much appreciated, thanks. I am using the json kit via github and also NSJSONserialization.

 {
   "proj_name": "Ant",
   "id": 
      [
          {
             "name": "David"
          },
          {
             "name": "Aaron"
          }
      ]
 },
 {
    "proj_name": "Dax",
    "id": 
         [
           {
             "name": "Adrian"
           },
           {
             "name": "Dan"
           }
         ]
  }

推荐答案

这里是仅选择名称并按字母顺序对它们进行排序的示例.用您的数据对象替换responseData.

Here is sample that selects just names and sort them alphabetically. Replace responseData with your data object.

NSMutableArray *names = [[NSMutableArray alloc] init];

NSError* error;
NSArray* json = [NSJSONSerialization 
    JSONObjectWithData:responseData
    options:kNilOptions 
    error:&error];

for (NSDictionary *proj in json) {
    NSArray *ids = [proj objectForKey: @"id"];

    for (NSDictionary *name in ids)
    {
        [names addObject: [name objectForKey: @"name"];
    }
}

NSArray *sortedNames = [names sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)];

这篇关于JSON数组和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆