Getting error when trying to set value/key pairs with SBJsonWriter - iphone

Getting the following error when trying to set value/key pairs:
2011-06-21 16:21:16.727 agent[94408:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<SBJsonWriter 0xab31230> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key key.'
Here is the code:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
[writer setValue:#"val" forKey:#"key"];
NSString *json = [writer JSONRepresentation];
NSLog([NSString stringWithFormat:#"json: #%", json]);

that is using the key-value coding from the (NSObject) category,
to use the dictionary interface:
import JSON.h then:
NSMutableDictionary * dict = [NSMutableDictionary new];
[dict setValue:#"val" forKey:#"key"];
NSLog(#"json: %#", [dict JSONRepresentation]);
p.s. NSLog accepts a format, so you don't need to make a string from a format to pass to it.

Related

How to get value from Nsstring in ios?

I am beginner in ios and in one of my activity : this is my nsstring and now I want to get "LocationId" from this string but I have problem .....I try to add this string in array and after that get LocationId but that I have also error ....
Nsstring *Str={"UserName":"ankitdemo","UserId":"08f11980-9920-4127-8fe7-78e1c40f6002","RoleName":"Doctor","RoleId":"87b4193c-1252-4505-a81b-2b49b8db57f3","FirstName":"Ankit","MiddleName":"","LastName":"Gupta","LocationId":"5f15648f-12ef-4534-a145-4044bc7c742e"}
Nsstring *LocationId=[NSString stringWithFormat:#"%#",[Str valueForKey:#"LocationId"]];
OR
NSMutableArray *location =[[NSMutableArray alloc]init];
[location addObject:self.WebService.ptr];
NSLog(#"location id is %#",location);
LocationId=[NSString stringWithFormat:#"%#",[[location objectAtIndex:0]valueForKey:#"LocationId"]];
NSLog(#"location id is %#",LocationId);
but I have error ....
ERROR
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x881d6d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key LocationId.'
Solve this problem.......
Do like this
You have to use JSON Parser...
NSDictionary *location = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error: &e];
NSLog(#"location id is %#",location);
LocationId=[NSString stringWithFormat:#"%#",[[location objectAtIndex:0]valueForKey:#"LocationId"]];
NSLog(#"location id is %#",LocationId);
The code you have provided has many problems and I doubt that you have copied and pasted it correctly. e.g Nsstring will not compile.
However, in general terms, you've created a string from something like a JSON dictionary, but the syntax is incorrect. And you are trying to get the value of a property that is not defined on NSString, which is the cause of your error.
You're looking for something like this:
NSDictionary *dictionary = #{ #"UserName" : #"ankitdemo",
#"UserId" : #"08f11980-9920-4127-8fe7-78e1c40f6002",
#"RoleName" : #"Doctor",#
#"RoleId" : #"87b4193c-1252-4505-a81b-2b49b8db57f3",
#"FirstName" : #"Ankit",
#"MiddleName" :#"",
#"LastName" : #"Gupta",
#"LocationId" : #"5f15648f-12ef-4534-a145-4044bc7c742e" };
NSString *locationId = dictionary[#"LocationId"];
Of course you get NSUnknownKeyException. NSString does not have LocationId accessor.
If you want to parse JSON, use JSON parsers, for example, NSJSONSerialization.
Oh, and don't use valueForKey: when you mean objectForKey:.
The code you provided won't compile, but I guess that you got some JSON as a NSString:
NSError *e;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error: &e];
if (!json)
NSLog(#"Error: %#",e);
else
NSString *locationID = [json objectForKey:#"LocationId"];

JSONKit invalid arguement when try to copy

I am parsing JSON data with JSONKit as NSMutableDictionary.
NSString *str = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *jsonResponse = [self.responseData objectFromJSONData];
NSMutableDictionary *newData = [[NSMutableDictionary alloc] init];
[newData addEntriesFromDictionary:[jsonResponse mutableCopy]];
When i do this i am getting this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableDictionary addEntriesFromDictionary:]: dictionary argument is not an NSDictionary'
I am trying to figure out what is causing this problem. I know that jsonResponse is an object of JKArray from my other experience.
I need help.
Thanks.
Try the following:
id object = [self.responseData objectFromJSONData];
NSLog(#"%#", [object class]);
Most likely your response is an array instead of a dictionary.
If you really want to convert the array into a dictionary, you could do something like this, using a self-defined key:
NSArray *array = [self.responseData objectFromJSONData];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:array forKey:#"posts"];
Though perhaps there are some better options if you could show me the contents of your array.

Objective-C JSON parsing error

I'm trying to parse this JSON Array:
http://www.ifanatic.hu/api/get_recent_posts/?dev=1
But I get this error:
2012-07-15 22:31:59.038 JSONTest[610:f803] -[__NSCFDictionary indexOfObject:]: unrecognized selector sent to instance 0x6a92850
2012-07-15 22:31:59.040 JSONTest[610:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary indexOfObject:]: unrecognized selector sent to instance 0x6a92850'
*** First throw call stack:
(0x13d7052 0x1568d0a 0x13d8ced 0x133df00 0x133dce2 0x236b 0xa23a59 0xa21e94 0xa22eb7 0xa21e4f 0xa21fd5 0x966f6a 0x3989bbd 0x3a565ea 0x3980298 0x3a5616b 0x3980137 0x13ab97f 0x130eb73 0x130e454 0x130ddb4 0x130dccb 0x12c0879 0x12c093e 0x2ea9b 0x1cb8 0x1c15)
terminate called throwing an exception
Here is my source:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* latestPosts = [responseString JSONValue];
NSDictionary* post = [latestPosts objectAtIndex:[latestPosts indexOfObject:0]];
NSString* title = [post objectForKey:#"title"];
label.text = [NSString stringWithFormat:#"Title: %#", title];
That JSON object's root element is translated to an NSDictionary when parsing the JSON. And NSDictionary doesn't respond to the
indexOfObject:
message. What you need to do is to use:
NSDictionary *post = [[latestPosts objectForKey:#"posts"] objectAtIndex:0];
etc.

NSMutableDictionary "unrecognized selector sent to instance"

-(void)saveDictionary:(int)counter
{
NSString *path=[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSString *test = [NSString stringWithFormat:#"%d", counter];
[theDictionary setObject:test forKey:#"Counter"]; <---- Error
[theDictionary writeToFile:path atomically:YES];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self saveDictionary:[_viewController counter]];
}
Error:
-[NSCFString setObject:forKey:]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString setObject:forKey:]: unrecognized selector sent to instance
I can Load the value for Key "Counter" from plist.
If I want to save the new value for same key "Counter" ... Error.
Need Help, spent hours.
bye
Here is the Code to initialize theDictionary:
-(void)initDictionary {
if (theDictionary == nil) {
NSString *path=[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
theDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
theString = [theDictionary objectForKey:#"Counter"];
}
}
Found it!
theString = [[NSString alloc] initWithFormat:[theDictionary objectForKey:#"Counter"]];
Thanks All!
This is because the object stored in theDictionary is actually an NSString and NSString doesn't contain a method called -setObject:forKey. Check your code for any places where theDictionary is being assigned and be sure that is actually an NSMutableDictionary.
check the initilization .. you could have done it like this .
NSMutableDictionary *dictoForSyncing = [[NSMutableArray alloc] init];
Sounds like theDictionary is a string instead of an NSMutableDictionary. Where is it created and what happended to it in the meantime?
This says that 'theDictionary' is not a dictionary at all. Most likely it was released earlier and some NSString has taken its place.
Are you using ARC? Where was 'theDictionary' defined.
And have you tried the zombies Instrument to track this down? That should help.
It seems that your property theDictionary isn't actually a dictionary, but a string (NSString). Where is theDictionary defined?
NSMutableArray *myObjFromFile = ....;
NSMutableDictionary *tmpDictFromFile =
[[[myObjFromFile objectAtIndex:xx] mutableCopy]; mutableCopy];
[tmpDictFromFile setObject:"YOUR OBJECT"
forKey:"YOUR KEY"];

problem in parsing JSON response in iphone

i am getting json data from this link
now i want data from "html_instructions": part
NSDictionary *result = [stringtext JSONValue];
NSLog(#"here");
NSArray *resultarr = [result objectForKey:#"routes"];
NSString *string;
for(NSDictionary *di in resultarr){
NSLog(#"for loop");
string = [[di objectForKey:#"legs"] objectForKey:#"steps"];
}
but after printing "for loop" in console it is throwing an exception
2011-05-20 16:16:26.997 speedymap[759:207] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x62a7d60
2011-05-20 16:16:26.999 speedymap[759:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x62a7d60'
please help me
i want html_instructiuons field value
Check if resultarr and di really contains anything or not.
NSDictionary *result = [stringtext JSONValue];
NSLog(#"here");
NSArray *resultarr = [result objectForKey:#"routes"];
CFShow(resultarr);
NSString *string;
for(NSDictionary *di in resultarr){
CFShow(di);
NSLog(#"for loop");
NSArray *tempArr = [[di objectForKey:#"legs"] objectForKey:#"steps"];
}
http://jsonviewer.stack.hu/#http://maps.googleapis.com/maps/api/directions/json?origin=delhi&destination=noida&waypoints=&sensor=true
Check the viewer and set the values accordingly. [di objectForKey:#"legs"] returns an array. the first object of that array is a dictionary which has the key steps. But that too returns another array.