如何从JSON数据重建NSAttributedString

时间:2014-03-29 15:39:55

标签: objective-c json nsattributedstring nsjsonserialization

我有这个NSAttributedString对象,我已经设法写在这样的文件中:

{
  "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
        }
      }
    }
  ]
}

现在我必须回读数据并重建NSAttributedString
任何想法?

1 个答案:

答案 0 :(得分:4)

反序列化您的JSON字符串以获取包含值的字典。然后根据需要解析这些位。

首先解析出字符串:

NSString *myString = [dictionaryFromJson objectForKey:@"string"];
NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:myString];

然后解析数组:

NSArray *attributes = [dictionaryFromJson objectForKey:@"runs"];

然后遍历数组并为其中的每个字典创建所需的属性:

for(NSDictionary *dict in attributes)
{
    NSArray *rangeArray = [dict objectForKey:@"range"];
    NSRange range = NSMakeRange([(NSNumber*)[rangeArray objectAtIndex:0] intValue], [(NSNumber*)[rangeArray objectAtIndex:0] intValue]); //you may need to make sure here your types in array match up and of course that you are in bounds of array

    NSDictionary *attributesDictionary = [dict objectForKey:@"attributes"];

    //I'll do the font as example
    NSDictionary *fontDictionary = [attributesDictionary objectForKey:@"font"];
    if(fontDictionary)
    {
        NSString *fontName = [fontDictionary objectForKey:@"name"];
        float fontSize = [[fontDictionary objectForKey:@"size"] floatValue];
        UIFont *myFont = [UIFont fontWithName:fontName size:fontSize];

        if(myFont)
        {
             [myAttributedString addAttribute:NSFontAttributeName value:myFont range:range];
        }
    }
}

然后继续使用其余的值,根据它们是否来自字典或数组来处理数据。

您还需要进行一些验证,空检查等,因此这段代码并不完整。