2

Ok, this is my first approach to JSONs in Objective-C (and i'm quite new to the last one too). i'm to get infos stored my json to use them in Objective-C, but when trying to load it i get null in response from NSLog(@"%@",allData); on. Can anybody please tell me what i am doing wrong? thanks in advance for your time and your patience. oh and if needed here's the json: http://jsonviewer.stack.hu/#http://conqui.it/ricette.json

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"json"];

NSError *error = nil;

NSMutableData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSLog(@"%@",JSONData);


NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSLog(@"%@",allData);

for (NSDictionary *diction in allData) {
    NSString *recipe = [diction objectForKey:@"recipe"];

    [array addObject:recipe];
}

NSLog(@"%@",array);
9
  • 1
    nothing as i use it only for NSMutableData and it looks like working fine. i'll check immediately Commented Jul 7, 2013 at 20:55
  • here's the error: 2013-07-07 22:57:27.146 prova_lettura_json[5547:c07] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 414.) UserInfo=0x71870d0 {NSDebugDescription=Unescaped control character around character 414.} 2013-07-07 22:57:27.147 prova_lettura_json[5547:c07] (null) Commented Jul 7, 2013 at 20:57
  • so the "xcode side" is correct in your opinion? if so thanks a lot, i've spent the entire afternoon after this.. i'll check then and let you know as soon as i get a solution! Commented Jul 7, 2013 at 21:03
  • 1
    Generally speaking, Xcode knows nothing about JSON and never uses it. Did you perhaps mean "Objective-C"? Commented Jul 7, 2013 at 21:19
  • 3
    Hint: Actually look at the value of error. Commented Jul 7, 2013 at 21:20

2 Answers 2

4

The JSONObjectWithData method has an error parameter, of which you can avail yourself in order to diagnose the problem. For example:

NSError *error = nil;
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData
                                                   options:0
                                                     error:&error];
if (error)
    NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

In your comments, you suggest that you received an error about "Unescaped control character around character 414." That would suggest an error in the JSON, itself, which you might want to validate by copying into http://jsonlint.com/ and see if it reports any issues.

In response to the broader question about whether there are any Objective-C issues, there are no coding errors, per se. I can't comment on the for loop which clearly assumes that allData is an array of dictionaries to which I cannot attest without seeing the JSON. But I'll take your word for it. But, yes, the Objective-C code looks fine (albeit, a little light on checking of the return values types and error objects).

For example, if you wanted some diagnostic assert statements that you could use during development, you might do something like:

NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSAssert(error, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

NSLog(@"%s: array=%@", __FUNCTION__, array);

NSAssert([allData isKindOfClass:[NSArray class]], @"allData is not an array");

for (NSDictionary *diction in allData) {
    NSAssert([diction isKindOfClass:[NSDictionary class]], @"%s: diction is not a dictionary (%@), __FUNCTION__, diction);

    NSString *recipe = [diction objectForKey:@"recipe"];

    NSAssert(recipe, @"%s: Did not find recipe key in diction (%@)", __FUNCTION__, diction);

    [array addObject:recipe];
}

If any of these errors were possible runtime errors in production, you'd replace assert statements with if statements that do the necessary error handling. But hopefully it illustrates the concept.

Sign up to request clarification or add additional context in comments.

2 Comments

The highlighted part resolved my issue. thank you for sharing all possible solutions
I"m glad that the answer helped you diagnose that invalid JSON was indeed the problem in your case. And perhaps it was jsonlint.com helped you diagnose the precise underlying issue. But I have removed the highlighting you added, as it made it look like that was a quote. IMHO, no further emphasis was needed.in this answer.
0

Problem in your response is that , string values are unable to concatenate.So, I have to manually remove those tabs and new lines.

At five places you are getting error i.e:

pelate.

pasta.

pomodoro.

saporiti).

\t

- (void)viewDidLoad
{
    NSString *urlStr=[NSString stringWithFormat:@"http://www.conqui.it/ricette.json"];

    urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *fileNameURL=[NSURL URLWithString:urlStr];

    NSLog(@"url is %@",urlStr);

    NSMutableURLRequest *filenameReq=[[NSMutableURLRequest alloc] initWithURL:fileNameURL];
    NSData *responseData=[NSURLConnection sendSynchronousRequest:filenameReq returningResponse:nil error:nil];

    NSString *responseString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    responseString=[[responseString componentsSeparatedByString:@"\n"] componentsJoinedByString:@""];
    responseString=[responseString stringByReplacingOccurrencesOfString:@"\t" withString:@""];

    responseData=[responseString dataUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"response String is %@",responseString);

    [NSCharacterSet characterSetWithCharactersInString:responseString];

    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: 0 error: &e];

    NSLog(@"JSON Array is %@ & error is %@",jsonArray,e);

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

2 Comments

I recommend not to touch the JSON text itself in the client - rather eliminate the root cause where the JSON has been created first place. In practice, we would never need to fiddle around with JSON text ourselves but would use an utility, like NSJSONSerialization to decode and encode.
Sorry, no it doesn't. Suppose you have a JSON string in the response, which has a tab character in there, you simple remove that from the string. You also simply remove control characters. Say, the string contains a CRLF: "abc\r\ndef" - you end up having a JSON string which is "abc\\def" which gets decoded to the string which prints "abc\def".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.