JSON for Objective-C returns error “Illegal start of token [r]”

寵の児 提交于 2019-12-13 06:56:48

问题


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);
}


来源:https://stackoverflow.com/questions/6834591/json-for-objective-c-returns-error-illegal-start-of-token-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!