I'm trying to access a webservice using the json framework.
Code:
NSDictionary *allData;
NSMutableDictionary *displayData;
NSString *string = [[NSString alloc] initWithFormat:#"http://localhost/Gangbucks.svc/GetDealList"];
NSURL *jsonURL = [NSURL URLWithString:string];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
self.allData = [jsonData JSONValue];
NSLog(#"allData value is1:%#", self.allData);
self.displayData = [[NSMutableDictionary alloc] initWithDictionary:self.allData];
NSLog(#"displayData value is2:%#", self.displayData);
allData works fine but I got an error on the displayData
2011-12-13 14:59:23.875 IPhone[352:207] -[__NSArrayM getObjects:andKeys:]: unrecognized selector sent to instance 0x59e1c20
2011-12-13 14:59:23.878 IPhone[352:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM getObjects:andKeys:]: unrecognized selector sent to instance 0x59e1c20'
*** Call stack at first throw:
Is it possible to pass data from NSDictionary to NSMutableDictionary ?
allData is apparently an NSArray, not an NSDictionary. You should go back and look at your JSON. The top-level there is probably an array.
Related
i need to send json dictionary as parameter, i am using afnetworking. While using following code i am getting an exception:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", nil];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"email":txt_email.text,#"password":txt_password.text,#"platform":#"iphone"};
NSLog(#"params:%#",params);
SBJsonWriter *jsonWriter=[[SBJsonWriter alloc]init];
NSString *paramsDicJSONN = [jsonWriter stringWithObject:params];
NSString *str_url=[NSString stringWithFormat:#"%#do_signup",BaseURLlogin];
[manager POST:str_url parameters:paramsDicJSONN success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"offerJSON: %#", responseObject);
Exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
Read the AFNetworking documentation in regard to sending POST data.
- (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters ...
The parameters argument expects an NSDictionary, not a JSON encoded NSString. Most likely just pass params and skip all the SBJsonWriter code.
I am fetching data from server using json. It is checked url is getting hit response is received, printed in console all values fetched from json. But dictionary and tried with array also both are showing null values by breakpoints but when printed in console showing data is fetched. Below is the code.
NSString *urlStr = [NSString stringWithFormat:#"http://server39.pivbfg.com/360ads/apps/ads/%#/android/1360/ord0.9109502528132325?json=1&package_url=%#",self.mStrPid, base64String];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:
[urlStr stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding]]];
NSLog(#"req-------------%#",request);
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [json_dict valueForKey:#"ads"];
request is going ok.
json_string is ok.
But json_dict printing values in console but showing null at breakpoints. What could be the reason for this. One thing is i am using ARC, does it affect this code. Please guide for the above.
This is the error: * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x9851e00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key ads.'* First throw call stack:
(0xb5012 0x13a9e7e 0x13dfb1 0xe565ed 0xdc28db 0xdc288d 0x613d 0x3d1707 0x3d1772 0x320915 0x320caf 0x320e45 0x329e57 0x5942 0x2ed697 0x2edc87 0x2eee8b 0x3001f5 0x30112b 0x2f2bd8 0x2202df9 0x2202ad0 0x2abf5 0x2a962 0x5bbb6 0x5af44 0x5ae1b 0x2ee6ba 0x2f053c 0x544d 0x2b65 0x1)
libc++abi.dylib: terminate called throwing an exception
Edited code
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"results\n%#",results);
NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [results valueForKey:#"ads"];
NSLog(#"dict-------------%#",arrAds);
Now the same problem is coming with the array arrAds. It is printing values in console but empty.
Well the error tells you that the property you are retrieving from the JSON is not a dictionary but a string. It looks like you json_string does not contain a valid JSON object.
In your example you'r also leaking:
NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [json_dict valueForKey:#"ads"];
You create a new NSMutableArray only to assing a new object to the same variable the next line. Also the object returned will not a none mutable version. You can just replace it with:
NSMutableArray *arrAds = [[json_dict objectForKey:#"ads"] mutableCopy];
I try to use codes
-(bool)checIfWorksOnJailbreak;
{
NSString *s = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Info.plist"];
NSLog(#"%#",s);
if([[NSFileManager defaultManager] fileExistsAtPath:s]) {
NSDictionary *plistDictionary = (NSDictionary*)[NSKeyedUnarchiver unarchiveObjectWithFile:s];
NSString *valueString = [plistDictionary objectForKey:#"SigerIdentity"];
if([valueString isEqualToString:#"Apple OS Application Signing"])
return true;
else
return false;
}
return false;
}
it always cause error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSKeyedUnarchiver initForReadingWithData:]:
incomprehensible archive version (-1)'
at line
NSDictionary *plistDictionary = (NSDictionary*)[NSKeyedUnarchiver unarchiveObjectWithFile:s];
Welcome any comment
NSKeyedUnarchiver (and NSKeyedArchiver) are not for encoding and decoding plists. Instead, they are used to serialize and deserialize objects that implement the NSCoding protocol. To read your plist data into a dictionary, you instead should use:
NSDictionary *plistDictionary = [NSDictionary dictionaryWithContentsOfFile:s];
I have the JSON in the format of
{"index":"0","name":"jemmy","age":"2"}
I need to extract the values stored and save it; I have done the following, but it doesn't work
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSCFString objectForKey:]:
unrecognized selector sent to instance 0x6671a10'
my code
NSDictionary *dictionary = [request responseHeaders];
SBJsonParser *parser = [SBJsonParser new];
id content = [responseString JSONValue];
NSDictionary *dealDictionary = content;
NSArray *array = [dealDictionary allKeys];
for (NSString *str in array)
{
NSDictionary *childDictionary = [dealDictionary objectForKey:str];
NSLog(#"%# ",[childDictionary objectForKey:#"name"]);
}
You may not understand how to use SBJSON, maybe a quick read through the documentation would be useful. First, you need to actually use the parser that you create:
SBJsonParser *parser = [SBJsonParser new];
NSDictionary *content = [parser objectWithString:[request responseString]];
Secondly, you can traverse your dictionary slightly easier as such:
NSEnumerator *enum = [content keyEnumerator];
id key;
while (key = [enum nextObject]) {
NSLog(#"key %# and object %#",key,[content objectForKey:key]);
}
I'm working with facebook connect and trying to handle the JSON object that i'm receiving.
I invoked the requstWithGraphPath method and need to get back a JSON object,
tried to parse it and getting an error:
SBJSON *parser = [[SBJSON new] autorelease];
NSData *data = [[NSData alloc] initWithData:result];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; -> in this line - "[__NSCFDictionary length]: unrecognized selector sent to instance"
NSArray *events = [parser objectWithString:jsonString];
What's the problem?
Can I get the string in an other way or parse the object differently?
Thanks.
If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoad:(id)result;
the parsing work has been done for you. Traverse the NSDictionary or NSArray to find the data you are looking for. If you are working with the delegate callback
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data;
you should initialize an NSString with the data, and use the category method that SBJSON adds to NSString for creating an id. That is assuming the data is data that constructs a string.
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
id result = [jsonString JSONValue];
Are you sure the error happens on that line, or does it happen on the line above?
If result is an NSDictionary (or CFDictionary, same thing), then it is already parsed and you do not need to do that yourself — and it could cause that error message too, on the line above.
The line:
data = [[NSData alloc] initWithData:result];
is almost certainly not what you want to do, as it is equivalent to
data = [result copy];
assuming that result is an NSData object (or NSMutableData), which I'm guessing it isn't.