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"]}}
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With