【问题标题】:iOS: JSON displays dictionary out of order. How to present a reordering?iOS:JSON 乱序显示字典。如何提出重新排序?
【发布时间】:2014-06-14 03:27:16
【问题描述】:

假设我们有以下字典:

dict = [NSDictionary dictionaryWithObjectsAndKeys:
                [NSNumber numberWithInt:currentItem], @"item number",
                [NSNumber numberWithInt:([[item valueForKey:@"section"] intValue]+1)], @"section number",
                currentDate, @"date of item",
                [NSNumber numberWithDouble:timeDifference], @"time difference in millis",
                        nil];

然后我得到以下输出:

{
  "time difference in millis" : 5.220093071460724,
  "section number" : 1,
  "date of item" : "28/04/2014 15:56:54,234",
  "item number" : 3
}

我使用以下代码将字典转换为 JSON:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; 
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];

如何操作 JSON 字符串显示其键的顺序。例如,我想要:

{
  "item number" : 3,
  "section number" : 1,
  "date of item" : "28/04/2014 15:56:54,234",
  "time difference in millis" : 5.220093071460724
}

或者别的什么。关键是我想控制这个过程。我如何得到它?我的第一个想法是编写一个解析器,以我想要的方式显示排序。

这里有类似的问题,但我的重点是操纵顺序,而不是仅仅重新创建我从字典中放置它的顺序。

JSON format: getting output in the correct order

Need JSON document that is generated to be in same order as objects inserted in NSMutableDictionary in iOS

【问题讨论】:

    标签: ios objective-c json dictionary


    【解决方案1】:

    NSDictionary 没有按定义排序。 如果您想拥有相同的顺序,最简单的方法是将所有内容包装到 NSArray 中。

    【讨论】:

      【解决方案2】:

      你不应该这样。字典没有顺序,写一些使用顺序的代码只会导致将来出现问题。

      也就是说,如果您愿意,您可以编写自己的代码,从您的(有序)键数组和值字典生成 JSON 字符串。

      【讨论】:

      • 我不想要它,但由于输出也需要由非程序员解释,他们认为更方便阅读的顺序将帮助他们不会被 json 语法分心。
      • 您不应该导出 JSON 供人类阅读。导出 CSV 文件并让他们将其导入到 excel 或类似的东西......
      • 嗯,我已经用 json 实现了很多东西。所以我可以将其转换为 CSV,但我认为应该有更有效的方法。你怎么看?
      • 有效只是针对情况使用适当的技术。 JSON 最适合机器阅读。 UI 最适合人类阅读 - 如何将数据获取到 UI 是一个偏好/可用性问题。
      【解决方案3】:

      重申这个问题:如何采用固有无序的输入,生成一个其规范固有无序的字符串,但控制该字符串的顺序。

      将字典重新格式化为数组可以让您控制输入顺序,但会产生不同的输出格式。

      我可以想象想要这样做的唯一原因是,如果希望将 JSON 字符串不作为 JSON 使用,而只是作为字符串使用。然后可以将问题重新表述为只是在词法上重新格式化字符串。

      它必须有多通用?我们可以假设 JSON 具有简单的标量值吗?那么……

      - (NSString *)reorderJSON:(NSString *)json keys:(NSArray *)orderedKeys {
      
          NSArray *splitJson = [json componentsSeparatedByString:@","];
          NSMutableArray *splitResult = [NSMutableArray array];
      
          for (NSString *key in orderedKeys) {
              for (NSString *splitPair in splitJson) {
                  if ([self jsonPair:splitPair hasKey:key]) {
                      NSString *trimmedSplitPair = [splitPair stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{}"]];
                      [splitResult addObject:trimmedSplitPair];
                  }
              }
          }
          NSString *joinedResult = [splitResult componentsJoinedByString:@","];
          return [NSString stringWithFormat:@"{%@\n}", joinedResult];
      }
      
      - (BOOL)jsonPair:(NSString *)pair hasKey:(NSString *)key {
      
          // pair should begin with double quote delimited key
          NSString *trimmedPair = [pair stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
          NSArray *splitPair = [trimmedPair componentsSeparatedByString:@"\""];
          return [splitPair[1] isEqualToString:key];
      }
      

      这样称呼它:

      - (void)testJson {
      
          NSDictionary *d = @{ @"time difference in millis": @5.220093071460724,
                               @"section number": @1,
                               @"date of item" : @"28/04/2014 15:56:54,234",
                               @"item number": @3};
      
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
          NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
      
          NSArray *orderedKeys = @[ @"item number", @"section number", @"date of item", @"time difference in millis"];
          NSString *result = [self reorderJSON:jsonString keys:orderedKeys];
          NSLog(@"%@", result);
      }
      

      【讨论】:

        猜你喜欢
        • 2020-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        相关资源
        最近更新 更多