How to get key/value pair from NSDictionary? - ios

I need little help with NSDictionary. How can I get 1 pair, lets say a value for "id" if I have dictionary
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
and it looks like this:
Thanks for Your help.

The shortest way:
NSNumber *number = allCourses[#"semacko"][#"id"];

Try this:
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
[allCourses enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];

NSDictionary *semacko = [allCourses objectForKey:#"semacko"];
NSNumber *number = [semacko objectForKey:#"id"];

NSNumber *number = allCourses[#"semacko"][#"id"];
or if you want to iterate all objects:
for(NSDictionary* course in allCourses) {
NSNumber *number = course[#"id"];
}

NSString *name =[[NSString alloc]initWithFormat:#"%#",[Dictionaryname objectForKey:#"key"]];
by this code you can access the value that corresponds to the key that specified in the objectforkey keyword

You can try:
NSNumber *courseID = [allCourses valueForKeyPath:#"semacko.id"];
For setting value:
- setValue:forKeyPath:

Related

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

iOS enumerate json remove objectkey

I'm struck how to enumerate JSON by remove first object in iOS programming as below
From
[{"001": {"name":"test", "url":"test"},"002":{"name":"test1", "url":"test1"},"003":{"name":"test2", "url":"test2"}}]
to
[ {"name":"test", "url":"test"},{"name":"test1", "url":"test1"},{"name":"test2", "url":"test2"}]
Pls help to recommend me or suggestion coding.
Thank you.
Try this,
NSArray *jsonArray = //parsedJsonArray
NSDictionary *values = [jsonArray objectAtIndex:0];
NSArray *valuesArray = [values allValues];
And the valuesArray will contain the data in format,
[ {"name":"test", "url":"test"},
{"name":"test1", "url":"test1"}, {"name":"test2", "url":"test2"}]
You can easily convert a json string to a NSMutableArray :
NSError *error;
// Get a NSMutableArray from the json string
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
// Remove the first object
[arrayResult removeObject:[arrayResult firstObject]];
jsonDataArray1=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"001"]];
jsonDataArray2=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"002"]];
jsonDataArray3=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"003"]];
jsonDataArrayFinal=[[NSMutableArray alloc]initWithObjects:jsonDataArray1,jsonDataArray2,jsonDataArray3 nil];
initialize all above arrays in viedidload

Parse from JSON response

I am getting the JSON response
(
{
Response = success;
UserId = 287;
}
)
I tried to parse the user id with below code
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataDictionary);
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
But am getting the user id ( 287 ).
Please suggest me that how to get user id without paraparentheses
Your response is not a dictionary, it's an array. So your code should look like this:
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataArray);
NSDictionary *dataDictionary = dataArray[0]; //Same as objectAtIndex:
NSString *userIDString = dataDictionary[#"UserID"]; //Same as objectForKey:
//If you're still getting parens try this:
//int userIDInt = [dataDictionary[#"UserID"] intValue];
You need to fetch integer value from your JSON response.
int userid = [[dataDictionary valueForKey:#"UserId"] intValue];
If getting parentheses in integer response too, then it is problem with JSON response recived. for a workaround you can use -
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
int userid = [[useridstring substringWithRange:NSMakeRange(1, useridstring.length - 2)] intValue]
EDIT --
You are getting an array in response, for this you have to use -
int userid = [[dataDictionary valueForKey:#"UserId"] firstObject];

Converting JSON ARRAY into NSNumber Arrays

I've retrieved data from a JSON web service and saved it into the following array
_soldamount =
(
0,
0,
0,
0,
"62.69",
"48.3",
81,
"59.83",
"162.57",
0,
"40.67",
)
I believe this array is saved as a string. how can I convert this array into an array of NSnumbers? Thanks for the help!
NSArray *_soldamount = #[ #0, #0, #0, #0, #"62.69", #"48.3", #81, #"59.83", #"162.57", #0, #"40.67"];
NSArray *numbers = [_soldamount valueForKey:#"doubleValue"];
creates an array of NSNumbers. The original array can contain NSNumber
or NSString objects.
You can do it using the following code:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&e];
What is stored in the json variable will depend on the JSON data. It is most commonly either an NSDictionary or NSArray, and it looks like yours would be an NSArray probably.
If these values are intended to be stored as numbers, your web service should be returning them as such. In other words, a value with quotes (") around it is a string regardless of whether or not the string is numerical.
If you do not have control of the web service and still wish to store these values as NSNumbers, you can use [NSNumber numberWithFloat:[string floatValue]] or you may wish to use [string doubleValue] if the strings may contain large values or high precision floating point values.
See Gavin's answer on how to use the NSJSONSerialization class if you aren't using it already.
NSError *error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *soldAmount = [json objectForKey:#"amount"]; // Your array of strings.
// Convert string array to number array
NSMutableArray *numberArray = [NSMutableArray array];
[soldAmount enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[numberArray addObject:[NSNumber numberWithFloat:[(NSString *)obj floatValue]]];
}];
use [NSnumber numberWithInteger:[string integerValue]]

NSJSONSerialization can't handle null values

I have some code that looks like this:
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray *arrRequests = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
// Loop through the array and generate the necessary annotation views
for (int i = 0; i<= arrRequests.count - 1; i++)
{
//now let's dig out each and every json object
NSDictionary *dict = [arrRequests objectAtIndex:i];
NSString *is_private = [NSString
stringWithString:[dict objectForKey:#"is_private"]];
...
It works when the value for is_private is 1 or 0, but if it is null it crashes with an exception on this line:
NSString *is_private = [NSString stringWithString:[dict objectForKey:#"is_private"]];
Is there a way to check if it is not null or handle this so that it is able to put nil into the NSString *is_private variable?
Thanks!
You should be able to handle it like so:
id value = [dict valueForKey:#"is_private"];
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;
Your problem has nothing to do with NSJSONSerialization and everything to do with the fact that you're passing a nil value to stringWithString:. Why not just simply that line to NSString *is_private = [dict objectForKey:#"is_private"];?
Also, why are you using an NSString to store a boolean value? An NSNumber would be much better-suited.
Why don't you just check if [dict objectForKey:#"is_private"] is nil or [NSNull null] before passing it to stringWithString:?

Resources