Cocoa:如何将NSAttributedString保存到JSON

Mar*_*man 4 cocoa json objective-c nsattributedstring

我有一个NSAttributedString对象作为自定义对象的属性.我需要以JSON格式将此自定义对象保存到磁盘.稍后我需要通过网络将此JSON数据发送到Java Server.
我无法使用对象的-(NSString) string方法,NSSAttributedString因为我需要能够从磁盘和服务器上重建属性字符串.

Abh*_*ert 11

NSAttributedString有两个属性:

  • 字符串
  • 属性"运行"的数组

每个"运行"都有:

  • 它适用的整数范围
  • 键/值属性的字典

使用JSON代表它很容易enumerateAttributesInRange:options:usingBlock:.

就像是:

{
  "string" : "Hello World",
  "runs" : [
    {
      "range" : [0,3],
      "attributes" : {
        "font" : {
          "name" : "Arial",
          "size" : 12
        }
      }
    },
    {
      "range" : [3,6],
      "attributes" : {
        "font" : {
          "name" : "Arial",
          "size" : 12
        },
        "color" : [255,0,0]
      }
    },
    {
      "range" : [9,2],
      "attributes" : {
        "font" : {
          "name" : "Arial",
          "size" : 12
        }
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个示例实现:

// create a basic attributed string
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"Hello World" attributes:@{NSFontAttributeName: [NSFont fontWithName:@"Arial" size:12]}];
[attStr addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(3, 6)];

// build array of attribute runs
NSMutableArray *attributeRuns = [NSMutableArray array];
[attStr enumerateAttributesInRange:NSMakeRange(0, attStr.length) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
  NSArray *rangeArray = @[[NSNumber numberWithUnsignedInteger:range.location],
                          [NSNumber numberWithUnsignedInteger:range.length]];

  NSMutableDictionary *runAttributes = [NSMutableDictionary dictionary];
  [attrs enumerateKeysAndObjectsUsingBlock:^(id attributeName, id attributeValue, BOOL *stop) {

    if ([attributeName isEqual:NSFontAttributeName]) { // convert font values into a dictionary with the name and size
      attributeName = @"font";
      attributeValue = @{@"name": [(NSFont *)attributeValue displayName],
                         @"size": [NSNumber numberWithFloat:[(NSFont *)attributeValue pointSize]]};

    } else if ([attributeName isEqualToString:NSForegroundColorAttributeName]) { // convert foreground colour values into an array with red/green/blue as a number from 0 to 255
      attributeName = @"color";
      attributeValue = @[[NSNumber numberWithInteger:([(NSColor *)attributeValue redComponent] * 255)],
                         [NSNumber numberWithInteger:([(NSColor *)attributeValue greenComponent] * 255)],
                         [NSNumber numberWithInteger:([(NSColor *)attributeValue blueComponent] * 255)]];

    } else { // skip unknown attributes
      NSLog(@"skipping unknown attribute %@", attributeName);
      return;
    }


    [runAttributes setObject:attributeValue forKey:attributeName];
  }];

  // save the attributes (if there are any)
  if (runAttributes.count == 0)
    return;

  [attributeRuns addObject:@{@"range": rangeArray,
                             @"attributes": runAttributes}];
}];

// build JSON output
NSDictionary *jsonOutput = @{@"string": attStr.string,
                             @"runs": attributeRuns};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonOutput options:NSJSONWritingPrettyPrinted error:NULL];

NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
exit(0);
Run Code Online (Sandbox Code Playgroud)