0

I'm having problem with parsing json data file on iOS. This is a sample from the data.json file:

var devs = [
{
"ident":"1",
"firstname":"Jan", 
"lastname":"Kowalski", 
"img":"http://www.placekitten.com/125/125", 
"tech":"iOS, HTML5, CSS, RWD",
"github":"placeholder",
"opensource":"1",
"twitter":"placeholder"
},
{
"ident":"2",
"firstname":"WacĹaw", 
"lastname":"GÄsior", 
"img":"http://www.placekitten.com/124/125",
"tech":"Android, Java, Node.js",
"github":"GÄsiorBKR",
"twitter":"wacek5565"
},

and so on.

With "normal" json files I use:

NSURLResponse *response;
NSError *myError;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL      URLWithString:@"http://somerailsapplication/posts.json"]     cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

Unfortunately this solution doesn't work in this case. Is there any chance to get this working without searching for specific string "var dev=[" and the last "]" in the downloaded data?

Szymon Fortuna
  • 400
  • 1
  • 11
  • 1
    why is your rails application doing that? – Daniel A. White Apr 16 '13 at 15:30
  • my rails application returns normal json - it's my own javascript-html5 based static website containing the file. In javascript it was easier to access elements this way, without using jQuery. Thanks for all the answers! – Szymon Fortuna Apr 16 '13 at 15:48

2 Answers2

3

The response is javascript, not JSON, so you won't be able to use a JSON parser directly. If you can't change the server output, the easiest thing would be to strip the beginning and end of the data, as you suggested. You could also embed the response in an HTML template and evaluate it in a webview, but that seems like a lot of more work.

lassej
  • 6,256
  • 6
  • 26
  • 34
0

Starting at the point where you've got the data:

NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSMutableString *dataAsString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[dataAsString deleteCharactersInRange:NSMakeRange(0, 11)];
data = [dataAsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

This turns the data into a string, removes the first 11 characters, turns it back into data, and then parses it as normal. (I've changed it to NSArray since your data is in an array)

Simon
  • 25,468
  • 44
  • 152
  • 266