I use JSON but there is exception [NSString objectForKey:] - json

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

Related

how to get the html format data in json in objective-c

The HTML data contains multiple lines with different anchor tags. The body on JSON like below format:
"description": "<div><b>Hiiiiiii,</b> officially known as <b>Hiiiiiii,</b>
Well you need this method to strip down the HTML tags from the string.
First you get the whole string in a variable like NSSting *wholeHtml = [jsonDictionary objectForKey:#"description"];.
-(NSString *) stringByStrippingHTML:(NSString *)inputString {
NSRange r;
NSString *toReturn;
while ((r = [inputString rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
toReturn = [inputString stringByReplacingCharactersInRange:r withString:#""];
return toReturn;
}
Then you call this method like this : NSString *outputString = [self stringByStrippingHTML:wholeHtml]; and you will get the required string in the variable outputString. You can also create a catagory of NSString and that would make your work more easy.
1 Take a string and store JSON key's description value in it .
eg: NSString str=[JSON value for key :#"description"];
2 Now Take a WebView and give this string to it .
eg:UIWebView webView = [[UIWebView alloc] init];
[webView loadHTMLString:str baseURL:nil];

Converting NSString to NSData for use in XCODE

I am getting data from the Yummly API and I would like to use it as though it were serialized JSON data. However, it is currently a string, and I cannot figure out how to turn it to data correctly. The code is as following:
NSString *searchParameters = #"basil"; //should be from text box
//NSError *error1 = nil;
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSString *searchResults = [NSString stringWithContentsOfURL:searchURL encoding:NSUTF8StringEncoding error:nil];
// Here, the search results are formatted just like a normal JSON file,
// For example:
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
// however it is a string, so I tried to convert it to data
NSData *URLData = [searchResults dataUsingEncoding:NSUTF8StringEncoding];
URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Somewhere over the last four lines, it didn't do what it was supposed to and there is no data in the data object. Any advice or quick hints in the right direction are much appreciated! Thank you1
Look at the error being returned from the NSJSONSerialization object like
NSError *error;
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
This might give you a hint of what's wrong. This should work though.
And why exactly are you doing URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];? You don't need to copy the data, if that's why you're doing that.
Plus, it seems like you're assuming to get an array as the top level object (judging by
/* [
"totalMatchCount":777306,
"facetCounts":{}
]
*/
but this is a dictionary. Basically you probably want a dictionary, not array. This it should be
/* {
"totalMatchCount":777306,
"facetCounts":{}
}
*/
But the error getting returned will tell you that.
It looks like you're over-complicating things a bit. You do not need to bring in this data as an NSString at all. Instead, just bring it in as NSData and hand that to the parser.
Try:
NSString *searchParameters = #"basil"; //should be from text box
NSString *searchURLName = [#"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];
NSURL *searchURL = [NSURL URLWithString:searchURLName];
NSData *URLData = [NSData dataWithContentsOfURL:searchURL];
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];
Note that you'll want to verify that the parsed JSON object is indeed an array as expected, and is not/does not contain [NSNull null].

Fast Enumeration in parse

I'm new to iOS and I'm trying to parse out JSON data. Nothing will log from inside of the enumeration, though vehicleActivity logs "vehicle (null).I am interested in logging the "LineRef" data. I'm assuming it is in NSString, but I tried with id object and still nothing.
NSDictionary *jsonParse = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray * vehicleActivity = [jsonParse objectForKey:#"VechicleActivity"];
NSLog(#"vehicle %#",vehicleActivity);
for (NSDictionary *dictionary in vehicleActivity ) {
NSDictionary *monitoredVehJourney = [dictionary objectForKey:#"MonitoredVehicleJourney"];
NSString *line = [monitoredVehJourney objectForKey:#"LineRef"];
NSLog(#"Line # %#",line);
Here is the JSON through a viewer
Thanks
though vehicleActivity logs "vehicle (null)"
That's why. If vehicleActivity is NULL (i. e., nil), then the fast enumeration wouldn't even begin.
Furthermore, you seem not to have read the documentation of the NSDictionary class. It iterates through keys, not values. So your for loop should be
for (NSString *key in vehicleActivity ) {
NSDictionary *dictionary = [vehicleActivity objectForKey:key];
// etc.
}
instead.
Furthermore, I believe you have a typo in your code regarding the key VehicleActivity. You wrote it as VechicleActivity.

iOS Parsing JSON Woes

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

ios5: Sending JSON data from the iPhone to REST using POST

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).