0

I have an HTTP Post request that returns a JSON object. I can view the return value as a string and it is perfect. What I am stuck on is converting this return value into something that can be parsed as a JSON object. I'm not sure of the conceptual steps, much less the code that I should be writing.

Here is the code that I have. It crashes the JSON serialization line because the line before it where I attempt to convert the return string into NSData results in a nil value. Not even sure if I need this step, but I can't find a successful solution.

Can anyone tell me what I am doing wrong? Thanks!

- (void) finished: (NSNotification *) n
{
    MyDownloader *d = [n object];
    NSData *data = nil;
    if ([n userInfo]) {
        NSLog(@"information retrieval failed");
    } else {
        data = d.receivedData;
        NSString *text=[[NSString alloc]initWithData:d.receivedData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", text);

        NSData *data = [NSData dataWithContentsOfFile:text];
        self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        if (self.response)
            [self parseJSONObject];
        else NSLog(@"The server has responded with something other than a JSON formatted object");
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"connectionFinished"
                                                  object:d];

}

1 Answer 1

1

You're using dataWithContentsOfFile, which is trying to load the data from a file in your local filesystem. Use this instead:

NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

However, as @MartinR points out, there's no need to convert d.recievedData to a string and then back to data. Just use it directly.

NSData *data = d.recievedData;
Sign up to request clarification or add additional context in comments.

3 Comments

Even that is not necessary, because d.receivedData already contains the JSON data. No need to convert it to a string and back.
@Jake King - your solution worked. @Martin R - can you please suggest a line of code where I can directly use d.receivedData? This is the part that I am hung up on - how to get from my received data into something that I can parse. Thanks to you both!
self.response = [NSJSONSerialization JSONObjectWithData:d.receivedData ...

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.