I request a JSON response from a home controlling device:
NSData* responseData = [NSData dataWithContentsOfURL:url];
The JSON data in responseData is complete and valid. However, if I try
NSDictionary* dict = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog("Error: %#", error);
it gives me the following error:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Duplicate key for object around character 0.) UserInfo=0x6a8b8e0 {NSDebugDescription=Duplicate key for object around character 0.}
I searched the web but couldn't find anything helpful so far.
Edit: The JSON response it quite long, so instead of posting it here, please find it here.
It looks like the JSON is fine by pasting it into http://jsonformat.com/ - maybe you found an Apple bug? Another way to try and validate would be to use a third-party iOS library and see if it gives you the same error? Say, TouchJSON?
I get the same error, only at random when the app runs. When the NSJSONSerialization fails I've checked the json object it chocks on using a JSON Viewer. The JSON is always OK. Bugs in NSJSONSerialization when it's called several times?
I got the same error. My JSON data passed JSON validator at http://jsonformatter.curiousconcept.com/ . However, I found two duplicated keys in my JSON (at the end of dictionary). After I removed those keys, NSJSONSerialization works smoothly.
Related
I have a strange issue while getting response from SVC webservice.
I have a response as below:
When I am fetching content from "AboutOrganization" key.
I am getting error as below:-
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Something looked like a 'null' but wasn't around character 324840.) UserInfo=0xc52345b0 {NSDebugDescription=Something looked like a 'null' but wasn't around character 324840.}
I have used NSJSONSerialization to get data from Webservice response.
I am not sure, But getting this type of Error because JSON object contents HTML escape sequence characters as below:
If I am right then give me solution for the same. And If i am wrong then guide me why i am getting this type of error.
Appreciate your time and help
Thank you in advance.
Am trying to integrate instagram in my app,while getting user details after getting access token,its showing error . Am appending data in NSData and trying to print it in connectionDidFinishLoading(NSURLConnection *)connection ( NSURLConnection Delegate) . While converting NSData to id ,its showing null .Also if i am converting NSdata to NSString am getting Response as
{"meta":{"error_type":"OAuthAccessTokenException","code":400,"error_message":"The access_token provided is invalid."}}{"meta":{"code":200},"data":{"username":"XXXX","bio":"","website":"","profile_picture":"http:sampleiamge.jpg","full_name":"samplename","counts":{"media":1,"followed_by":0,"follows":0},"id":"sampleID"}}
If am printing the json as id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
getting error as
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0xa967bc0
{NSDebugDescription=Garbage at end.}
Tried all jsonreading option ,but no result
Any hep will be appreciable.
Thanks
You could also have a look at the InstagramKit which does this fairly straight forward. https://github.com/shyambhat/InstagramKit
There's a demo app so you can see how the authentication is done and request a user's details in just a few lines of code. You don't really need to mess around with the access token data format.
It seems like you are not authenticate.
There is a project in GitHub that implements a simple UIViewController that performs the Instagram auth process step by step:
https://github.com/Buza/Instagram-Auth-iOS
You can see all process from request token to error management.
Hope it helps!
The response occurs when the access_token is invalid, try printing (NSLog) out the URL your are making the request and make sure the access_token is correctly passed.
I am trying to make an HTTP PUT request to a CouchDB server. I am converting an NSString instance to NSData. I then convert this NSData instance to an NSArray and attempt to PUT this to CouchDB. So something like this:
//convert string to NSData
NSData *docData = [#"{\"name\":\"nick\"}" dataUsingEncoding:NSUTF8StringEncoding];
//NSData to NSArray
NSArray *arrayJson = [NSArray arrayWithObjects:[NSJSONSerialization JSONObjectWithData:docData options:kNilOptions error:nil],nil];
I am then creating an HTTP PUT request using AFNetworking (which is rad btw ;))
The problem is that this creates a json string which looks like:
[{"name":"nick"}]
This is valid JSON but Couch complains with 400 Bad JSON. Removing the [ ]s fixes the problem. I'm sure these brackets are the result of converting NSData to NSArray but I'm not sure how else to accomplish this using NSJSONSerialization. Can anyone help?
Thanks!
Edit
For clarity sake let me explain the problem I was having further. I am creating a document using the CouchDB HTTP API using a PUT HTTP request. The document could be hand coded JSON and that is why I have this parsing challenge. Couch expects a single document to create. Therefore it expects a single JSON object. NOT an array of them. That seems to be why [{"key":"value"}] returns a 400 HTTP response from Couch. Even if the array contains a single object. Seems a bit picky that the API wouldn't just infer correctly based on the array length.. but I guess you could argue either way. See the selected answer below. This is what I was looking for. Thanks to all those who responded!
You can let NSJSONSerialization do the conversion from Foundation object to string. This guarantees proper escaping and makes the code more readable.
If you have a key-value pair as in your sample above, you could do:
NSError* error = nil;
NSDictionary* jsonDict = #{#"name": #"nick"};
NSData* putData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
You should be able to directly put that into the content of your PUT request, without wrapping it in an additional array. If the endpoint that handles the request requires you to send an array, you should create the array as an Foundation object (NSArray) and serialize that as JSON before sending it to the server:
NSArray* jsonArray = #[#{#"name": #"nick"}];
The title of your question is "Deserialize JSON without wrapping in [ ]" - Shouldn't that be "Serialize JSON without wrapping in [ ]"?
I changed it, please change it back if I misunderstood your question.
I have a method for downloading a file as file_name.zip to the documents directory. However, if I receive an error, such as 'file does not exist', the library is writing the JSON payload to file_name.zip.
How do we check for JSON error in requestFinished:?
responseString or responseData is always null.
You probably want to check the request.responseStatusCode and check against a 404 error. But honestly you should look into AFNetworking. ASIHTTPRequest is no longer supported and AFNetworking has success/failure blocks.
when i try to parse the response returned from a web service i got this stack:
JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6e76c30 {NSLocalizedDescription=Unrecognised leading character}"
)
My code is like this:
if(request.responseStatusCode==200)
{
NSLog(#"so far, this block of code works");//this log is displayed
//parse the response
NSArray *array=[[request responseString]JSONValue];
//processing the array and do whatever
In this thread they talking about an old version of the JSON library and how to update it, please help me figure out what should i do.
EDIT:
when trying to parse the response, i wanted to see why the server return, so an NSLog like so:
if(request.responseStatusCode==200)
{
NSLog(#"the request is %#", request.responseString);
//parse the response
NSArray *array=[[request responseString]JSONValue];
//processing the array and do whatever
give me this stack:
the request is <br />
<b>Warning</b>: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed in <b>/homepages/25/xxxx/htdocs/my app/webservices/index.php</b> on line <b>39</b><br />
<br />
<b>Fatal error</b>: Call to undefined function sendResponse() in <b>/homepages/25/xxxxx/htdocs/my app/webservices/index.php</b> on line <b>57</b><br />
2012-01-20 15:10:45.491 my-iPhone-application[882:11603] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6ebd450 {NSLocalizedDescription=Unrecognised leading character}"
)
EDIT 2:
My application sent an array that is supposed to be received and processed in the web services. So one example of how the array received looks like is:
(
Mairie,
\"Pr\\U00e9fectures et sous-pr\\U00e9fectures\",
\"Auto-\\U00e9cole\"
)
The strange ant-slashes and 00 are the é caracter. Am i wrong to use them in my data? Is this which is causing my problem?
The error pretty much says it all, the parser does not consider the JSON string is it reading to be valid JSON. "Unrecognised leading character" means that it found something other than a { or [ character as the first character in the string returned from [request responseString]
If you post the raw JSON we might be able to help you point out exactly what is wrong with the response.
HTH
If request.responseString returns <br /> then it looks like your server is returning HTML and HTML isn't JSON ;)
Your use of the JSON library is correct, it's either your request or (more likely given the response) your server thats broken.
On the plus side, you have accidentally done some error testing on your app :)