this response i am getting from web service. how to fetch only cities record??
Data = (
{
Cities = (
{
CityCode = 21;
Name = Cork;
Numbers = (
{
Number = 2349990;
PauseOne = 3;
PauseTwo = 3;
}`enter code here`
);
}
)
NSDictionary *cities = myJson[#"Data"][0][#"Cities"][0];
NSLog(#"City Name is = %#", cities[#"Name"]);
NSLog(#"City Code is = %d", [cities[#"CityCode"] intValue]);
This Code is Finally used for you:
NSMutableArray *arrFinalAllCities = [[NSMutableArray alloc]init];
NSMutableArray *arrData = [responseObject objectForKey:#"Data"];
for (int a=0; a<arrData.count; a++)
{
NSMutableArray *arrCity = [[arrData objectAtIndex:a] objectForKey:#"Cities"];
for (int b=0; b<arrCity.count; b++)
{
[arrFinalAllCities addObject:[arrCity objectAtIndex:b]];
}
}
NSLog(#"%#",arrFinalAllCities);
the response u hav posted looks like an nsdictionary. not a server returned json. can u post the exact json returned by server? tip: convert nsdata to nsstring and post dat
Related
Apologies if this is a novice question, but I've been struggling to figure this out with no luck. I'm trying to pull a users' twitter timeline using the AFOAuth2Manager framework. Everything makes sense except the returned JSON object is an array and the entire object is one giant object. I obviously want to break it up into different elements and store them in a dictionary, but have not been able to figure it out so far.
This is a VERY partial example of what the array object looks like. The complete object is this with about 20 or so more tweets with this format attached. I will post the entire json object if requested, but it seems pretty pointless to post the entire thing.
Heres my code:
[manager GET:#"/1.1/statuses/user_timeline.json?screen_name=jack"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject ) {
self.object = responseObject;
NSLog(#"Success: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSLog(#"object is a nsarray class");
} else if ([responseObject isKindOfClass:[NSDictionary class]]){
NSLog(#"object is a nsdictionary class");
} else {
NSLog(#"object is a different class");
}
NSArray *response = [NSArray arrayWithObject:responseObject];
NSLog(#"count %ld", [response count]);
NSData *dataFromTwitter = [NSKeyedArchiver archivedDataWithRootObject:self.object];
NSError *parseError = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:&parseError];
NSLog(#"response Dict: %#", responseDict);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&e];
NSLog(#"jsonArray: %#", jsonArray);
NSError *jsonError2 = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&jsonError2];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(#"jsonArray2 - %#",jsonArray);
}
else {
NSLog(#"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
NSLog(#"error %#", jsonError2);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Mon Feb 29 01:18:05 +0000 2016";
entities = {
hashtags = (
);
symbols = (
);
urls = (
);
"user_mentions" = (
{
id = 14616957;
"id_str" = 14616957;
indices = (
0,
7
);
name = "Jason Del Rey";
"screen_name" = DelRey;
},
{
id = 19040598;
"id_str" = 19040598;
indices = (
8,
18
);
name = "\U0ca0_\U0ca0";
"screen_name" = MikeIsaac;
},
{
id = 46063;
"id_str" = 46063;
indices = (
19,
30
);
name = "Hunter Walk";
"screen_name" = hunterwalk;
}
);
};
"favorite_count" = 12;
favorited = 0;
geo = "<null>";
id = 704113377920978944;
"id_str" = 704113377920978944;
"in_reply_to_screen_name" = DelRey;
"in_reply_to_status_id" = 704112911116013568;
"in_reply_to_status_id_str" = 704112911116013568;
"in_reply_to_user_id" = 14616957;
"in_reply_to_user_id_str" = 14616957;
"is_quote_status" = 0;
lang = en;
place = "<null>";
"retweet_count" = 0;
retweeted = 0;
source = "Twitter for iPhone";
text = "#DelRey #MikeIsaac #hunterwalk this changes everything";
truncated = 0;
user = {
"contributors_enabled" = 0;
"created_at" = "Tue Mar 21 20:50:14 +0000 2006";
"default_profile" = 0;
"default_profile_image" = 0;
description = "#withMalala!";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 11433;
"follow_request_sent" = "<null>";
"followers_count" = 3458722;
following = "<null>";
"friends_count" = 1859;
"geo_enabled" = 1;
"has_extended_profile" = 1;
id = 12;
"id_str" = 12;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 25944;
location = "California, USA";
name = Jack;
notifications = "<null>";
"profile_background_color" = EBEBEB;
"profile_background_image_url" = "http://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_tile" = 0;
"profile_image_url" = "http://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_image_url_https" = "https://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_link_color" = 990000;
"profile_sidebar_border_color" = DFDFDF;
"profile_sidebar_fill_color" = F3F3F3;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = jack;
"statuses_count" = 19066;
"time_zone" = "Pacific Time (US & Canada)";
url = "<null>";
"utc_offset" = "-28800";
verified = 1;
};
},
You show no code in your question, in a comment you state you have a responseObject but not how you came by it.
The JSON you are getting from somewhere will be text, you may have it as an NSString, NSData, an NSArray whose elements are these, etc.
You need to obtain that text and then parse it as JSON, the NSJSONSerialization class will handle the parsing for you, the first line of its description states:
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
Once you have those Foundation objects - arrays, dictionaries, strings, numbers, etc. you can extract the fields you are interested in.
Once you've written some code to do this if it doesn't work and you are stuck ask a new question showing your code and someone will probably be able to help you further.
HTH
My "saveData" dictionary looks like this:
{
Adresser = {
"completed_status" = {
finished = 4;
total = 5;
};
...
}
And my "dOrder" dictionary looks like this
{
id = 1924;
name = Adresser;
order = 0;
}
And the snippet of code
NSDictionary * saveData = [self dbReadFormData:_objectID];
for (NSDictionary * dOrder in dictFormSections[#"order"]) {
NSString * segName = dOrder[#"name"];
NSLog(#"finished: %#", saveData[segName][#"completed_status"][#"finished"]);
NSLog(#"total: %#", saveData[segName][#"completed_status"][#"total"]);
NSString * vFinished = [saveData objectForKey:saveData[segName][#"completed_status"][#"finished"]];
NSString * vTotal = [saveData objectForKey:saveData[segName][#"completed_status"][#"total"]];
NSString * sSection = [NSString stringWithFormat:#"%# - %# / %#", segName, vFinished, vTotal];
[rx insertSegmentWithTitle:sSection atIndex:rx.numberOfSegments animated:NO];
}
The NSLog's return the correct values. (4 and 5) But the NSStrings are nil.
What am I doing wrong?
Thank you!
As mentioned by #Arc676, you have :
NSLog(#"finished: %#", saveData[segName][#"completed_status"][#"finished"]);
and
NSString * vFinished = [saveData objectForKey:saveData[segName][#"completed_status"][#"finished"]];
However, they are not the same. Shouldn't vFinished be like:
NSString* vFinished = saveData[segName][#"completed_status"][#"finished"];
I'm trying to get information out of this Dictionary that was created from a JSON string. The JSON string is returned from the server and is put in a dictionary. That dictionary is passed to myMethod that is suppose to break it down so I can get the information that each record contains.
The "Recordset" is an Array. The Record is also an array of dictionaries.
How do I get to the dictionaries? I keep getting NSDictionaryM objectAtIndex: unrecognized selector sent to instance
Recordset = (
{
Record = (
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1691;
MODvc50Name = "10/12 Series 2";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1687;
MODvc50Name = "10/4";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1686;
MODvc50Name = "10/6";
},
etc .. etc... ( about 100 records )
Here is what I have
- (void) myMethod : (NSDictionary*) dictionary {
//INITIAL
NSArray * arrRecordSet = [dictionary objectForKey:#"Recordset"];
NSArray * arrRecord = [arrRecordSet objectAtIndex:0];
NSDictionary * theRecord = [NSDictionary dictionaryWithObjects:arrRecord forKeys:[arrRecord objectAtIndex:0]];
for (int i = 0; i < arrRecord.count; i++) {
NSLog(#"MODMAKlMakeKey: %#", [theRecord objectForKey:#"MODMAKlMakeKey"]);
}
}
Try this
NSArray * arrRecord = [arrRecordSet objectForKey:#"Record"];
Try to check first if the return of [dictionary objectForKey:#"Recordset"] is really a dictionary or an array.
To do this:
if([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSArray class]]) {
//object is array
}
else if ([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSDictionary class]]) {
//object is dictionary
}
I begin in Ios dev and I got some troubles to manipulate an array create by Json :
I call in my app a web Service which return me data :
{evenements =(
({
dateEvenement ={
1 = "01-01-2013";
2 = "02-01-2013";
3 = "03-01-2013";
4 = "04-01-2013";
};
idEvenement = 61;
nbrInvite = 1;
nomEvenement = "My event Name";
nomUtilisateur = "Lucas ";
}
),
);
}
I'm able to get all the values by the following code except for "dateEvenement" :
NSArray *msgList;
msgList = [ jsonResults objectForKey:#"evenements" ];
for (NSDictionary *evenements in msgList) {
for (NSDictionary *evenement in evenements ) {
NSString *idEvenement = [evenement objectForKey:#"idEvenement"];
NSString *nomUtilisateur = [evenement objectForKey:#"nomUtilisateur"];
NSString *nomEvenement = [evenement objectForKey:#"nomEvenement"];
NSString *nbrInvite = [evenement objectForKey:#"nbrInvite"];
NSArray *dates = [ evenement objectForKey:#"dateEvenement" ];
}
}
Can you help me for getting datas of "dateEvenement"
Well in your JSON the dateEvenement isn't an Array but a dictionary:
NSDictionary *dates = [ evenement objectForKey:#"dateEvenement"];
for(NSNumber *key in dates) {
NSString *dateString = [dates objectForKey:key];
NSLog(%# : %#, key, dateString);
}
As declared in your JSON example the key's for the dictionary are numbers, thus you should NSNumber object for the key type.
I have an array width this values:
array: (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
},
{
id = 3;
name = "Bibendum Ornare";
value = "123.42";
},
{
id = 4;
name = "Lorme Ipsim";
value = "586.24";
}
)
What I need to do is get each 'value' and sum it all. Im declaring a new array to take each value:
self.valuesArray = [[NSArray alloc] init];
But how can I do it? Thanks for your answer!
double sum = [[array valueForKeyPath:#"#sum.value"] doubleValue];
You can read more on collection operators here
You have already declared array so i will use your. I also assume your first array(which contains data set above) is an array called myFirstArray(of type NSArray)
int sum =0;
self.valuesArray = [[NSMutableArray alloc] init];
for(NSDictionary *obj in myFirstArray){
NSString *value =[obj objectForKey:#"value"];
sum+= [value intValue];
[self.valuesArray arrayWithObject:value];//this line creates a new NSArray instance which conains array of 'values'(from your dictionary)
}
NSLog("The sum of values is: %d", sum);
NSLog("The array of \'values\' is : %#",self.valuesArray );
double sum=0.0;
for (YourDataObject *d in array) {
sum+=[[d getValue] doubleValue];
}
try this -
float totalValue = 0.0f;
for (int i = 0 ; i< [array count]; i++) {
totalValue +=[[[array objectAtIndex:i] objectForKey:#"value"] floatValue];
}