I am trying to send data in the JSON format to the REST api. When sending a parameter the web service does not return any data but instead gives the following error:Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
This is because the parameter cannot be read by the web service.
But if I add this parameter directly to the URL the correct results are returned Eg:http://localhost:8080/de.vogella.jersey.final/rest/notes/63056
The following is the code for sending the parameters:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost:8080/de.vogella.jersey.final/rest/notes/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *postString = #"{\"notes\":\"63056\"}";
NSLog(#"Request: %#", postString);
// NSString *postString = #"";
[request setValue:[NSString stringWithFormat:#"%d",[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSLog(#"Return Data%#",returnData);
//Getting the task types from the JSON array received
NSMutableArray *jsonArray =[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(#"jsonArray is %#",jsonArray);
taskTypes =[[NSMutableArray alloc]init ];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#",error);
} else {
for(NSDictionary *taskType in jsonArray) {
[taskTypes addObject:[taskType objectForKey:#"TaskName"]];
}
}
Any suggestions?
Your error "JSON text did not start with array or object and option to allow fragments not set" could mean two things:
You're specifying that you expect the response object to be in JSON format and it is not (for example, this would happen if you're using an AFJSONRequestOperation and the server returns something other than JSON)
Fix: Get a hold of the server code and make sure it returns a valid JSON object
You have not specified that you're okay with receiving something other than JSON
Fix: If you're using AFNetworking, pass in NSJSONReadingAllowFragments to [NSJSONSerialization JSONObjectWithData:options:error:] on your subclass of AFHTTPClient (Shout out to Cocoa error 3840 using JSON (iOS) for this answer).
Related
I want to parse json data which contains html but there is a problem
I made a parser with this lines but always I got this error: The operation couldn’t be completed. (Cocoa error 3840.)
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];
You need to fix the incoming JSON object. You will need to encode that HTML in your web-service (whatever that may be). You should be able to see the issue when you run your JSON through a validator like JSONViewer or JSONLint.
I'm trying to get informations from MySQL data base, I did this :
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/php_files/additif.php?keyword=Gélatine"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSDictionary *serverResponseArray = [NSJSONSerialization JSONObjectWithData:dataURL options:NSJSONReadingMutableContainers error:nil];
but application crashes with message : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
The problem is that when I change the value of keyword to E120 or another string in the strURL,everything is fine and application runs without any problems. I checked the database and it contains a row with Gélatine informations and I checked also the strURL and it's correct.
Any suggestions please ?
I've been bashing my head against a wall for a bit.
I have a rails back-end that is returning JSON to my iOS app. I'm using rails' default return for rendering my object in JSON for me automatically. I'm having trouble with the errors it returns.
The JSON I get for errors is {"errors":{"email":["can't be blank"],"password":["can't be blank"]}}.
I use ASI for handling the request.
-(void) requestFinished:(ASIFormDataRequest *)request {
NSDictionary *data = [[request responseString] JSONValue];
Doing the above code make data become:
{
errors =
{
email = (
"can't be blank"
);
password = (
"can't be blank"
);
};
}
Now this gives me issues trying to parse it out. I'd like to be able to access each element of errors, and its associated value.
When I try to loop through the elements, I do something like:
for (NSDictionary *error in [data objectForKey:#"errors"])
This will give me email and password, but they are of type __NSCFString, not NSDictionary. I haven't been able to find a way to get the value for either email or password. Does anyone have an idea on how to parse this out?
Thanks!
This should work, note that response has the same structure than your 'data' NSDictionary.
NSDictionary *fields = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSArray alloc] initWithObjects:#"one", #"two", nil],
#"A",
[[NSArray alloc] initWithObjects:#"three", #"four", nil],
#"B",
nil];
NSDictionary *response = [[NSDictionary alloc] initWithObjectsAndKeys:fields, #"errors", nil];
NSLog(#"Dictionary: %#", [response objectForKey:#"errors"]);
for (NSString *field in [response objectForKey:#"errors"])
for (NSString* error in [response valueForKeyPath:[NSString stringWithFormat:#"errors.%#", field]])
NSLog(#"%# %#", field, error);
The output will look like this:
Dictionary: {
A = (
one,
two
);
B = (
three,
four
);
}
A one
A two
B three
B four
Well i dont have Mac right now but i'm trying to help you if it doesnt work let me know i will correct it tomorrow.
-(void) requestFinished:(ASIFormDataRequest *)request
{
NSArray *data = [[request responseString] JSONValue];
NSDictionary *dict = [data objectAtIndex:0];
NSDictionary *dict2 = [dict valueForKey:#"errors"];
NSLog(#"email = %#, password = %#",[dict2 valueForKey:#"email"], [dict2 valueForKey:#"password"]);
}
I am using the new ios5 "NSJSONSerialization" function to obtain some tech-news from a website. I seem to have everything working OK, up until the point when I try to parse the NSDictionary into an NSArray. I have included the code here. The first console test (test 1) is working great - I get a console full of returned json data. But at the second console test (test 2 - the one that checks the contents of the nsarray), gives this message: "Array returned: (null)". Any ideas? Is it because I reused the error variable, maybe? I'm stumped.
Here's the code:
// create the string for making the api call to the website
NSString* theURL = [NSString stringWithFormat:#"http://pipes.yahoo.com/pipes/pipe.run?_id=9DfJELfJ2xGnjAQWJphxuA&_render=json"];
// declare and assign variables necessary to generate the actual url request
NSError* err = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:theURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
// make the actual url request - get the data from yahoo pipes, in json format
NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// assign the entire result to a dictionary
NSDictionary *resultsDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
//*** test 1: use the console to test results:
NSLog(#"NSDictionary returned: %#",resultsDictionary);
// parse the whole returned list of items (in dictionary form) into a large array
NSArray* arrayOfReturnedItems = [resultsDictionary objectForKey:#"items"];
//*** test 2: view the items returned (in the console)
NSLog(#"Array returned: %#",[arrayOfReturnedItems objectAtIndex:0]);
i read information in my database i use JSON but there is exception
'NSInvalidArgumentException', reason: '-[NSCFString objectForKey:]: unrecognized selector sent to instance 0x603dfb0'
I think this part :
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *str = [[[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding] autorelease];
NSArray *array = [str JSONValue];
if (!array)
return;
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
[fmt setDateFormat:#"yyyy-MM-dd"];
for (NSDictionary *dict in array) {
NSDate *d = [fmt dateFromString:[dict objectForKey:#"eve_date"]];
NSLog(#"%#",d);
[eventPHP addObject:[Events eventsNamed:[dict objectForKey:#"title_event"] description:[dict objectForKey:#"description"] date:d]];
}
}
"pass the linker a special flag, ‘-ObjC’. Adjusting the build settings of my project to include this flag in the ‘Other linker flags’"
according to:
http://beatworm.co.uk/blog/computers/using-categories-on-objective-c-classes-in-a-static-library/
EDIT:
Why it is terminating?
EDIT2:
OK, not exactly sure (as I've never done this type of coding), but given the json data:
{"event":[
{"eve_date":"2011-12-18","eve_time":"00:00:06","title_event":"Google event","description":"Google event for IT student"},
{"eve_date":"2011-12-29","eve_time":"00:00:08","title_event":"microsoft event","description":"microsoft event for IT student"}
]}
The first object is an array labeled "event" which might be throwing you off.
So, try replacing this:
for (NSDictionary *dict in array) {
NSDate *d = [fmt dateFromString:[dict objectForKey:#"eve_date"]];
NSLog(#"%#",d);
[eventPHP addObject:[Events eventsNamed:[dict objectForKey:#"title_event"] description:[dict objectForKey:#"description"] date:d]];
}
with:
NSArray *array2 = [array objectForKey:#"event"];
for (NSDictionary *dict in array2) {
NSDate *d = [fmt dateFromString:[dict objectForKey:#"eve_date"]];
NSLog(#"%#",d);
[eventPHP addObject:[Events eventsNamed:[dict objectForKey:#"title_event"] description:[dict objectForKey:#"description"] date:d]];
}
using: Problem getting JSON contents with JSONValue
Not sure if that will work, but if it does, it will make more sense to me.
I solve exception by change location files class of JSON but the event doesn't
display in calendar .
the calendr is display but didn't contain any event
hint: when i put url in browser the content of database display