Parsing NSStrings to ensure a correctly formed JSON string within XCode
Asked Answered
V

1

6

I am reading string data from a PLIST which I am using to create a JSON string (incidentally for use within Facebook Connect).

NSString *eventLink = [eventDictionary objectForKey:EVENT_FIND_OUT_MORE_KEY];
NSString *eventLinkEscaped = [eventLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *eventName = [eventDictionary objectForKey:EVENT_NAME_KEY];
NSString *eventDescription = [eventDictionary objectForKey:@"Description"];
NSString *eventImageAddress = [eventDictionary valueForKey:@"Image URL"];
if ([eventImageAddress length] == 0)
{
    eventImageAddress = NO_EVENT_IMAGE_URL;
}
// Publish a story to the feed using the feed dialog
FBStreamDialog *facebookStreamDialog = [[[FBStreamDialog alloc] init] autorelease];
    facebookStreamDialog.delegate = self;
    facebookStreamDialog.userMessagePrompt = @"Publish to Facebook";
    facebookStreamDialog.attachment =[NSString stringWithFormat: @"{\"name\":\"%@\",\"href\":\"%@\",\"description\":\"%@\",\"media\":[{\"type\":\"image\",\"src\":\"%@\",\"href\":\"%@\"}]}", eventName, eventLinkEscaped, eventDescription, eventImageAddress, eventLinkEscaped];
[facebookStreamDialog show];

All this works well, but certain event descriptions (4 out of approx. 150) the text that appears in the dialog is blank. I have found the obvious candidates, i.e., the description contains the " character for instance or the copyright symbol. My question is, is there an easy method call, such as stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding that will ensure that any dodgy characters are escaped or ignored?

Thanks in advance,

Dave

Vernettaverneuil answered 10/2, 2010 at 10:17 Comment(1)
Actually on further investigation, the copyright symbol is fine it was actual LF/CR in the text for 2 of the events and the " character for the other 2.Vernettaverneuil
N
2

I don't think there is an easy way to escape the problem strings. If you need JSON support anywhere else in your code, consider using one of the existing JSON parsing/generator frameworks such as yajl-objc or SBJSON. Either of these will let you build your response as Foundation objects (NSArray/NSDictionary) and then call a single method to generate the appropriate JSON. Your code will be cleaner and you have the benefit that both of these frameworks are well-tested.

If just need to generate this one bit of JSON, your best bet is probably to manually walk over the input strings, replacing potential problem characters with the appropriately escaped versions. Is is not as bad as you might think. Take a look at the source for SBJsonWriter

Nashbar answered 16/2, 2010 at 3:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.