Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS JSON Parse not working (returns null dictionary)

I use the NSJSONSerialization's JSONObjectWithData:data options: error: to parse JSON data returned from a server.

Now for the options parameter I use: NSJSONReadingAllowFragments. You can look below and see the actual JSON (where I believe the problem is).

The error message I get is:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x6895da0 {NSDebugDescription=Invalid value around character 0.}

Any idea how to fix it?

JSON =

{"name":"Johan Appleseed",
"email":"[email protected]",
"phone":"+4121876003",
"accounts":{
    "facebook":[true,1125],
    "twitter":[false,null],
    "homepage":[true,"http:\/\/johnAplleseed.com\/index.html"]}}
like image 491
byteSlayer Avatar asked Aug 22 '12 10:08

byteSlayer


3 Answers

Probably you have some unprintable character that you cannot see. Try this:

NSData *jsonData = ...
const unsigned char *ptr = [data bytes];

for(int i=0; i<[data length]; ++i) {
  unsigned char c = *ptr++;
  NSLog(@"char=%c hex=%x", c, c);
}

To verify you don't have unprintable characters at the beginning or end of the data.

EDIT: to clarify, just run the above on your JSON dictionary - the one that fails to parse.

like image 183
David H Avatar answered Oct 18 '22 02:10

David H


Ive acctualy discovered the problem to be the fact that the return from the URL is an HTML page, ant there all these html, head, and body tags around the actual response, so it can't be parsed. This is a good Q&A on how to remove the HTML tags from the response (after it has been changed into a string) : Remove HTML Tags from an NSString on the iPhone

like image 25
byteSlayer Avatar answered Oct 18 '22 04:10

byteSlayer


I had the same problem for a while, I just figured out that if I'm pulling data from a webpage let's say PHP page, there should not be any HTML tags in that page. So a structure like:

<html>
<body>
<?php

?>
</body>
</html>

will ruin your result. turning it into:

<?php

?> 

worked for me.

like image 33
Behrad3d Avatar answered Oct 18 '22 03:10

Behrad3d