JSON for Objective-C returns error “Illegal start

2019-09-12 07:18发布

问题:

I am attempting to connect to a web page and return a JSON string. This string simply needs to be parsed in JSON and returned into an NSArray that I have waiting for it. The problem is that JSON doesn't always return the results. Sometimes, it works well. Sometimes, it returns (null), citing the error below.

self.accounts = nil; // Clear the NSArray

NSString *post = [NSString stringWithFormat:@"username=%@", username.text];
NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]];

// Submit login data
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString: @"http://###.#####.###/app/getaccts.php"]];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
[request setHTTPBody: postData];

// Retreive server response
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];

accounts = [[content JSONValue] allValues]; // Parse JSON string into the array
NSLog(@"Array: %@", accounts);

The page I am submitting to returns this:

{"1":"856069060", "2":"856056407"}

JSON logs the following error:

-JSONValue failed. Error is: Illegal start of token [r]

回答1:

Can I get a little more info ... specifically, I'd like you to check the return value of your sendSynchronousRequest so can you make this change and rerun your test:

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (returnData == nil) {
    NSLog(@"ERROR: %@", err);
} else {
    NSLog(@"DATA: %@", returnData);
}