Getting a JSON string from an array of NSValue objects holding CGPoint structs

I am a big fan of SBJson, and let’s face it, who isn’t? (Thanks Stig!) It has served me well for a long time, and only occasionally do I have to do any real work when it comes to serializing and deserializing JSON.

My current needs required me to take an NSArray of NSValue objects that each hold a CGPoint value, and send that down the wire via JSON. Simply passing the array inside the proxyForJson method halts the processing, so as I looked into it further I discovered that I needed to set up a utility function to create an NSDictionary that could be handled by the SBJson framework. Here is the code that I am using:

+ (NSArray *)jsonCompatibleArrayOfCGPoints:(NSArray *)pts
{
    NSMutableArray *pointsArr = [NSMutableArray array];
    for (int idx = 0; idx < [pts count]; idx++)
    {
        CGPoint pt = [pts[idx] CGPointValue];
        [pointsArr addObject:@ { @"x" : [NSNumber numberWithFloat:pt.x], @"y" : [NSNumber numberWithFloat:pt.y] }];
    }
 
    return [NSArray arrayWithArray:pointsArr];
}

BTW, great sadness today as it is the anniversary of the untimely and far too early passing of Duane Allman, lost in a motorcycle accident this day in 1971.

Leave a Reply