How to get value from Nsstring in ios? - iphone

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

Related

displaying JSON data with the help of dictionaries and array

I get the following error
[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x75a8e20
2013-04-20 08:56:14.90 MyApp[407:c07] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]:
unrecognized selector sent to instance 0x75a8e20'
This is my first hands on working with JSON. I get the above mentioned error when I try to run the first piece of code where URL is a flickr url. When I use the photos as key it print the array and app abruptly quits.
#define flickrPhotoURL [NSURL URLWithString: #"http://api.flickr.com/services/rest/?format=json&sort=random&method=flickr.photos.search&tags=rocket&tag_mode=all&api_key=12345&nojsoncallback=1"]
- (void)viewDidLoad
{
[super viewDidLoad];
//this line of code will be executed in the background to download the contents of the flickr URL
dispatch_async(flickrBgQueue, ^{
NSData* flickrData = [NSData dataWithContentsOfURL:flickrPhotoURL]; //NOTE: synchronous method...But we actually need to implement asynchronous method
[self performSelectorOnMainThread:#selector(appFetchedData:) withObject:flickrData waitUntilDone:YES]; //when data is available "appFetchedData" method will be called
});
}
- (void)appFetchedData: (NSData *)responseData
{
//parsing JSON data
NSError *error_parsing;
NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
NSArray* photo_information = [flickr_json objectForKey:#"photos"];
NSLog(#"Photo Information: %#",photo_information);
NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];
humanReadable.text = [NSString stringWithFormat:#"Owner is %#",[photo objectForKey:#"Owner"]];
}
However when I run the same piece of code by replacing the key "photos" with "loans" and use the following URL and code
#define flickrPhotoURL [NSURL URLWithString: #"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
- (void)appFetchedData: (NSData *)responseData
{
//parsing JSON data
NSError *error_parsing;
NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
NSArray* photo_information = [flickr_json objectForKey:#"loans"];
NSLog(#"Photo Information: %#",photo_information);
NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];
humanReadable.text = [NSString stringWithFormat:#"loan amount is %#",[photo objectForKey:#"loan_amount"]];
}
, the app sets the correct information on the humanredable.text property. Am I using the wrong key for the first JSON ?
Firstly, thanks for publishing your Flickr API key as-is! It will be super useful for me to perform identity theft some day.
Second, another big thanks for not having read the data you got back. It starts like this:
{"photos":{"page":1, "pages":1792, "perpage":100,
^^^^^^^^^^
So the object for the key photos is a dictionary, not an array, thus,
NSArray* photo_information = [flickr_json objectForKey:#"photos"];
is wrong. Did you mean this instead:
NSArray* photo_information = [[flickr_json objectForKey:#"photos"]
objectForKey:#"photo"];
? Also, below when you construct the human readable description,
[photo objectForKey:#"Owner"]
is wrong, it should be
[photo objectForKey:#"owner"]
instead.

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.

Error with NSJSONSerialization - Invalid type in JSON write (Menu)

I have an App using core data with 3 entities with very similar attributes. The relationship is such as:
Branch ->> Menu ->> Category ->> FoodItem
Each entity has an associated class: example
I am trying to generate JSON representation of the data in sqlite database.
//gets a single menu record which has some categories and each of these have some food items
id obj = [NSArray arrayWithObject:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&err];
NSLog(#"JSON = %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
But instead of JSON, i get a SIGABRT error.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Menu)'
Any ideas how to fix it or how to make the entity classes (Branch, Menu etc) JSON serialization compatible?
That's because your "Menu" class is not serializable in JSON. Bascially the language doesn't know how your object should be represented in JSON (which fields to include, how to represent references to other objects...)
From the NSJSONSerialization Class Reference
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
This means that the language knows how to serialize dictionaries. So a simple way to get a JSON representation from your menu is to provide a Dictionary representation of your Menu instances, which you will then serialize into JSON:
- (NSDictionary *)dictionaryFromMenu:(Menu)menu {
[NSDictionary dictionaryWithObjectsAndKeys:[menu.dateUpdated description],#"dateUpdated",
menu.categoryId, #"categoryId",
//... add all the Menu properties you want to include here
nil];
}
And you could will use it like this :
NSDictionary *menuDictionary = [self dictionaryFromMenu:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuDictionary options:NSJSONWritingPrettyPrinted error:&err];
NSLog(#"JSON = %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
There is a class method isValidJSONObject on NSJSONSerialization that tells you if a object can be serialised. As Julien pointed out you probably have to convert your object to a NSDictionary. NSManagedModel provides some handy methods to get all your attributes for your entity. So you could create a category for NSManagedObject that has a method to convert it over to a NSDictionary. This way you don't have to write a toDictionary method for each entity you want to convert to a dictionary.
#implementation NSManagedObject (JSON)
- (NSDictionary *)toDictionary
{
NSArray *attributes = [[self.entity attributesByName] allKeys];
NSDictionary *dict = [self dictionaryWithValuesForKeys:attributes];
return dict;
}
You can use + isValidJSONObject: method of NSJSONSerialization class. If it is not valid, you can use - initWithData:encoding: method of NSString.
- (NSString *)prettyPrintedJson:(id)jsonObject
{
NSData *jsonData;
if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
NSError *error;
jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject
options:NSJSONWritingPrettyPrinted
error:&error];
if (error) {
return nil;
}
} else {
jsonData = jsonObject;
}
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
I had the key switched with the value : #{value :#"key"}
It should be #{#"key":value}

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

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

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.