I want to send NSDictionary data with AFNetworking POST method and get result from server.
this my NSDictionary :
{
"category_id" = "-1";
"city_id" = "-1";
"degree_id" = "-1";
"experience_id" = "-1";
industries = (
{
id = 2;
},
{
id = 4;
},
{
id = 3;
}
);
"position_id" = "-1";
"salary_id" = "-1";
skills = (
{
aa = id;
},
{
aa = asdasda;
}
);
"type_id" = "-1";
}
when send this NSDictionary my server receive my data like this :
{
"category_id" = "-1";
"city_id" = "-1";
"degree_id" = "-1";
"experience_id" = "-1";
industries = (
2,
4,
3
);
"position_id" = "-1";
"salary_id" = "-1";
skills = (
id,
asdasda
);
"type_id" = "-1";
}
I'm so confused from this !!!
industries & skills are array of dictionary in my NSDictionary but when server to receive don't show key and only show value in array!!!
please guide me about that.
this is my POST method :
self.params = [[NSMutableDictionary alloc]init];
[self.params setObject:[NSNumber numberWithInteger:[self.object.jobCategory integerValue]] forKey:#"category_id"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.jobCity integerValue]] forKey:#"city_id"];
[self.params setObject:self.object.industry forKey:#"industries"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.educationDegree integerValue]] forKey:#"degree_id"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.experience integerValue]] forKey:#"experience_id"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.jobType integerValue]] forKey:#"type_id"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.jobSalary integerValue]] forKey:#"salary_id"];
[self.params setObject:[NSNumber numberWithInteger:[self.object.jobPosition integerValue]] forKey:#"position_id"];
[self.params setObject:[NSMutableArray array] forKey:#"skills"];
[[self.params objectForKey:#"skills"] addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"id",#"aa", nil]];
[[self.params objectForKey:#"skills"] addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"asdasda",#"aa", nil]];
//NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.params options:NSJSONWritingPrettyPrinted error:nil];
//NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",self.params);
NSString* path = [NSString stringWithFormat:#"%#%#" , [PublicMethods getStrings:#"url"],[PublicMethods getStrings:#"searchJob"]];
[self.network callPOSTWebServiceWithPath:path AndWithParameters:self.params withCallback:^(NSDictionary *result)
{
NSLog(#"%#",result);
if ([[result objectForKey:#"result"]boolValue])
{
NSLog(#"%#",[result objectForKey:#"data"]);
}
else
{
//error accured
}
}];
It is a very easy issue.
You send a string data in which includes NSDictionary nested NSArray.
But you send it to the server.
Your code of industries and skills which there is the same key in the array.
So when it sent to the server, and then returned value without key.That's correct.
Wanna see your returned value with key.Just change your id likes id1, id2, id3. As to it ,the variable of aa is just like that.
Finally , you'll see the key with value be returned .
Good luck!
Related
Noob here. I recently started working with objective C, and currently I am stuck with dictionary concept. I want to create a json object as shown below:
{"UserData": {
"Name": Mike Smith,
"Age": 32,
"category": [1,2,3],
"Weekly Data": [
{"Monday" : [1.0,2.0,3.0]},
{"Tuesday": [1.0,2.0,3.0]}
]
}
}
I wrote the following piece of code which doesn't give the desired result. I wonder if someone could help me.
-(NSString*)populateUserPreferences
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *categorydata = [[NSMutableArray alloc] init];
NSMutableArray *weeklydata = [[NSMutableArray alloc] init];
for (int i=0;i<4; i++)
{
[categorydata addObject:[NSNumber numberWithInt:i]];
}
NSMutableArray *mondaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[mondaydata addObject:[NSNumber numberWithInt:j]];
}
NSMutableArray *tuesdaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[tuesdaydata addObject:[NSNumber numberWithInt:j]];
}
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
[weeklydata addObject: monday ];
[weeklydata addObject: tuesday ];
}
[dict setObject:[NSString stringWithFormat:"Mike Smith"] forKey:#"Name"];
[dict setObject:[NSNumber numberWithInteger:32.0] forKey:#"Age"];
[dict setObject:categorydata forKey:#"category"];
[dict setObject:weeklydata forKey:#"Weekly Data"];
NSString * userdata = [dict JSONRepresentation];
NSLog(request);
NSDictionary *userdataJson = [NSDictionary dictionaryWithObject:dict forKey:#"userData"];
return [userdataJson JSONRepresentation];
}
Thanks in advance for looking into it.
Apoorva
The mistake is when creating the monday and tuesday dictionary.
// mondaydata & tuesday is just array.
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
This code is mistake since you did not assign the dictionary properly (where is the key for the dictionary?). Instead you should do:
NSDictionary *mondayDict = [[NSDictionary alloc] init];
[mondayDict setObject:mondaydata forKey:"Monday"];
NSDictionary *tuesdayDict = [[NSDictionary alloc] init];
[tuesdayDict setObject:tuesdaydata forKey:"Tuesday"];
Then you can add mondayDict and tuesdayDict to your array weeklydata.
ps. just a note, name your variable meaningfully. For example, mondaydata is not descriptive enough. You should use mondayArr for example. To easily identify it is an array. Just a normal coding practice to share.
NSDictionary * dict = #{#"UserData": #{
#"Name": #"Mike Smith",
#"Age": #32,
#"category": #[#1,#2,#3],
#"Weekly Data": #[
#{#"Monday" : #[#1.0,#2.0,#3.0]},
#{#"Tuesday": #[#1.0,#2.0,#3.0]}
]
}
};
NSError * error = nil;
NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
// Do what you want
}
NSArray *arrayBlockData = [data objectForKey:kData];
for (NSDictionary *dictTicket in arrayBlockData) {
NSString *blockId = [dictTicket objectForKey:#"block_id"];
[dictJson setObject:blockId forKey:#"block_id"];
[self.arrblockIds addObject:[dictTicket objectForKey:#"block_id"]];
}
[arrkeysAndValues addObject:dictJson];
NSLog(#"arrkeysAndValues %#",arrkeysAndValues);
reponse is :
arrKeysValues (
{
"block_id" = 624;
},
{
"block_id" = 624;
},
it should be :
arrKeysValues (
{
"block_id" = 623;
},
{
"block_id" = 624;
}
Your question isn't clear. But the code sample on how you put NSDictionary inside NSMutableArray is
NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setValue:#623 forKey:#"block_id"];
NSMutableDictionary *dict2 = [NSMutableDictionary new];
[dict2 setValue:#624 forKey:#"block_id"];
NSMutableArray *newArray = [NSMutableArray new];
[newArray addObject:dict];
[newArray addObject:dict2];
NSLog(#"%#", newArray);
how to print the key event_id on label.
"all_data" = (
{
"company_logo" = "http://mbdbtechnology.com/projects/officeapp/uploads/event/Voxev\U00e6rket_logo_stort.png";
"event_id" = 8;
"event_name" = "Dit nye kontor i Voxev\U00e6rket";
"event_sort_desc" = "Voxev\U00e6rket tilbyder landsd\U00e6kkende kontorer til ny opstartede";
},
{
"company_logo" = "http://mbdbtechnology.com/projects/officeapp/uploads/event/Image_jpg_2_288X200.jpg";
"event_id" = 7;
"event_name" = "Sunday Special only for women";
"event_sort_desc" = "Declarations of war At midnight on 31 July \U2013 1 Aug, French 2";
},
try this:
NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//responseData is an NSData object containing the jSON
NSMutableArray *allData = [jsonDict objectForKey:#"all_data"];
for (NSDictionary* dict in allData)
{
NSString *eventID = [dict objectForKey:#"event_id"];
NSLog(#"event ID : %#",eventID);
}
Im using foursquare API to get some locations around me, but when the name of that place wasn't in english, the name will be like follows:
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
i tried to convert the response to a UTF-8 but nothing changed.
Here is my code:
-(void)setUpLocations{
NSURL *url = [NSURL URLWithString: #"https://api.foursquare...."];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Response: %#",[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"]);
}
And the log result is:
contact = {
};
id = 51712507498ec4e8c5ae9f48;
likes = {
count = 0;
groups = (
);
};
location = {
address = Abdoun;
cc = JO;
city = Amman;
country = Jordan;
distance = 3819;
lat = "31.95406043797281";
lng = "35.88095228186612";
};
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
restricted = 1;
stats = {
checkinsCount = 43;
tipCount = 2;
usersCount = 23;
};
verified = 0;
},
Any Suggestions ??
EDIT:
here is how i extract the data from the dictionary:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
namesArray = [[NSArray alloc]initWithArray:[self removeWhiteSpaces:[dic valueForKey:#"name"]]];
-(NSArray *)removeWhiteSpaces:(NSDictionary *)dic{
NSString *str = [NSString stringWithFormat:#"%#",dic];
NSString *str2 = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *secondString = [str2 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *thirdString = [secondString stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *forthString = [thirdString stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *fifthString = [forthString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *items = [fifthString componentsSeparatedByString:#","];
return items;
}
And in the UITableView:
cell.textLabel.text = [NSString stringWithFormat:#"Name: %# ",[namesArray objectAtIndex:indexPath.row] ];
Update
After trying #Martin R answer i got the same results:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
NSString *value =[dic valueForKey:#"name"];
NSLog(#"%#", value);
UILabel *lbl = [[UILabel alloc]initWithFrame:self.view.frame];
lbl.numberOfLines = 0;
lbl.text = [NSString stringWithFormat:#"%#",value];;
[self.view addSubview:lbl];
and here is an image of the result
There is no problem.
NSLog() calls the description method of NSDictionary and NSArray, and that prints all non-ASCII characters as \Unnnn escape sequence.
If you extract the string values from the dictionary and print that you will see
that everything is correct.
Simple example:
NSDictionary *dict = #{ #"currency": #"€" };
NSLog(#"%#", dict);
// Output: { currency = "\U20ac"; }
NSString *value = dict[#"currency"];
NSLog(#"%#", value);
// Output: €
UPDATE: The problem seems to be in your removeWhiteSpaces: method, because
NSString *str = [NSString stringWithFormat:#"%#",dic];
already uses the description method to convert the dictionary to a string,
and the following stringByReplacingOccurrencesOfString calls are a (sorry!) very bad
method to fix that.
You should access the dictionary keys with objectForKey instead, or enumerate
the dictionary with for (NSString *key in dic) { ... } and build the desired
array.
UPDATE 2: From the JSON data (posted in chat discussion) it seem that you just need
NSArray *itemsArray = json[#"response"][#"groups"][0][#"items];
NSArray *namesArray = [itemsArray valueForKey:#"name"];
Note that "groups" is an array with one element.
Try to use this one..
[NSString stringWithUTF8String:]
I have following array,I have one array with multiple dictionaries,I need to get that dictionaries for same prod_type and create another array with unique key
nsarray
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
I need following array format from above array
nsarray=
{
abc=
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
}
pqr=
{
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
}
xyz=
{
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
}
}
Use NSPredicate to get desirable result.
NSString *selectedCategory=#"abc";
//filter array by category using predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"prod_type == %#", selectedCategory];
NSArray *filteredArray = [yourAry filteredArrayUsingPredicate:predicate];
NSDictionary *abcDic = [NSDictionary dictionaryWithObject:filteredArray forKey:#"abc"];
[yourNewAry addObject:abcDic];
You can repeat it for other
Here a nice explanation of it predicates
Use this code if you want a fully automated solution (without having to re-specify each prod_type):
NSMutableArray *keys = [originalArray mutableArrayValueForKey:#"prod_type"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:keys];
NSArray *uniqueKeys = orderedSet.array;
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for(NSString *key in uniqueKeys){
NSPredicate *keyPredicate = [NSPredicate predicateWithFormat:#"prod_type = %#",key];
NSDictionary *keyDictionary = [NSDictionary dictionaryWithObject:[originalArray filteredArrayUsingPredicate:keyPredicate] forKey:key];
[resultArray addObject:keyDictionary];
}
NSLog(#"%#",resultArray);
try like this,
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"prod_type"];//here you'l get all the prod_type values in an array
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"prod_type CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
EX:-
NSMutableArray *array =[[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjects:#[#"abc",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
[array addObject:dict];
[array addObject:dict1];
[array addObject:dict2];
NSLog(#"%#",array);
(
{
name = abc;
value = 100;
},
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
)
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"name"];
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"name CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
{
abc = (
{
name = abc;
value = 100;
}
);
pqr = (
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
);
}