Question

I use the following code to create a JSON file.

// Some data in keys and vals.
NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:vals forKeys:keys];
NSError* writeError = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary 
                   options:NSJSONWritingPrettyPrinted error:&writeError];   
NSString* path = @"json.txt";
[jsonData writeToFile:path atomically:YES];

How can I output a JSONP file? Is there a Cocoa framework I can use?

Update: In the meantime, I used a quick-and-dirty solution: I read in the JSON file just written before to the disc and add the missing JSONP-function to the string. Then, I write the file a second time. I think that's not worth being the answer to my question. So I will leave this question open to a smarter solution.

Was it helpful?

Solution

You could convert the JSON data to a string, wrap it in your function call and then write it to a file. Example:

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:NULL];
NSMutableString *jsonString = [[[NSMutableString alloc] initWithData:jsonData 
                                                            encoding:NSUTF8StringEncoding] autorelease];
[jsonString insertString:@"functionCall(" atIndex:0];
[jsonString appendString:@");"];
[jsonString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];

(I'm using a mutable string here for better memory efficiency.)

OTHER TIPS

I don't know objective-c or Cocoa. (I use python on MacOS to create JSNOP responses), but it's a simple thing to do. The basic idea is to wrap the JSON data in a javascript function call:

functionCall({"Name": "Foo", "Id" : 1234, "Rank": 7});

The tricky part is that the function name, "functionCall", is set by the browser and AFAIK the name of that query parameter is not standardized. jQuery uses jsonCallback. Other's use json or callback. So the request url must be checked for that callback name and that function name must be used to wrap the json data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top