I have a NSDictionary and I don't know how I can retrieve the value of "#mode" and "#route" (this is from a json response).
How I can do that?
Thanks!
This is the NSDictionary :
{
"#mode" = WALK;
"#route" = "Rue University";
distance = "17.513516908661757";
duration = 13000;
endTime = "2011-04-29T12:08:59.395-04:00";
from = {
geometry = "{\"type\": \"Point\", \"coordinates\": [-73.57120386807037,45.503820214186405]}";
lat = "45.503820214186405";
lon = "-73.57120386807037";
name = "Rue University";
};
legGeometry = {
length = 3;
points = "{mvtG`k``MOd#ME";
};
startTime = "2011-04-29T12:08:46.395-04:00";
steps = {
walkSteps = (
{
absoluteDirection = NORTHWEST;
becomes = false;
distance = "17.513516908661757";
elevation = "";
lat = "45.503820214186405";
lon = "-73.57120386807037";
stayOn = false;
streetName = "Rue University";
},
{
absoluteDirection = NORTH;
becomes = true;
distance = "0.0";
elevation = "";
lat = "45.50390573910769";
lon = "-73.57139257694809";
relativeDirection = RIGHT;
stayOn = false;
streetName = "street transit link";
}
);
};
to = {
geometry = "{\"type\": \"Point\", \"coordinates\": [-73.571363,45.503971]}";
lat = "45.503971";
lon = "-73.571363";
name = "Station McGill";
stopId = 32;
};
Looks like object at index 0 is a NSDictionary.
NSDictionary *dict = [array objectAtIndex:0];
NSString *route = [dict objectForKey:#"#route"];
Try this:
[myDictionary objectForKey:#"#mode"];
Given an NSDictionary dict, you can retrieve the value corresponding to the key #mode using:
[dict objectForKey:#"#mode"];
Two possibilities:
1) The NSMutableArray is an array of JSON formatted strings.
2) The NSMutableArray is an array of NSDictionaries.
If its #1, then you need to use the Cocoa JSON stuff to decode the JSON string into an NSDictionary:
NSDictionary* aDict = [[myArray objectAtIndex:0] JSONValue];
OR
NSDictionary* aDict = [theArray objectAtIndex:0];
The JSON stuff is available here http://code.google.com/p/json-framework/
Then this should work:
NSString* theMode = [aDict objectForKey:#"#mode"];
NSLog(#"the mode is %#, as read from the dictionary %#", theMode, aDict);
--Tom
Related
In my application ,the dictionary value contains following content.How to retrieve the each and store it new array
contryArray(
{
checka0 = Thailand;
checka1 = Brazil;
checka10 = Marocco;
checka11 = Thailand;
checka12 = Jordan;
checka13 = Colombia;
checka14 = Kuwait;
checka3 = Mexico;
checka4 = "Saoudi Arabia";
checka5 = Chili;
checka7 = Australia;
checka8 = Malta;
checka9 = "South Africa";
checkb0 = havana;
checkb1 = Santos;
checkb10 = Casablanca;
checkb11 = Bangkok;
checkb12 = Aqaba;
checkb13 = Havana;
checkb14 = Shuwaikh;
checkb3 = Veracruz;
checkb4 = Jeddah;
checkb5 = "San Antonio";
checkb7 = Maersk;
checkb8 = Maraxklokk;
checkb9 = Durban;
checkc0 = 1;
checkc1 = "0.7";
checkc10 = 1;
checkc11 = "1.2";
checkc12 = 1;
checkc13 = "1.4";
checkc14 = 1;
checkc3 = "0.9";
checkc4 = "0.8";
checkc5 = "0.9";
checkc7 = "2.7";
checkc8 = "0.8";
checkc9 = "0.9";
}
For ex: checka0-checka14 in one array, Here the problem is checka2 and checka6 is not available, Im new bee in xcode,Please help me to retrieve
Your question is not clear. Possibly you need to get all keys in your dictionary and separating each item with specific word in it(checka/checkb/checkc).
If that is the case then,
You will get all the keys using:
NSArray *dictKeys = [yourDictionary allKeys];
You can implement this in multiple ways, one of them:
For storing it in same array:
for (NSString *key in [yourDictionary allKeys])
{
[yourArray addObject:[yourDictionary objectForKey:key]];
}
For storing it in seperate arrays:
for (NSString *key in [yourDictionary allKeys])
{
if([key rangeOfString:#"checka"].location != NSNotFound)
{
//add checka to first array
[yourFirstArray addObject:[yourDictionary objectForKey:key]];
}
else if([key rangeOfString:#"checkb"].location != NSNotFound)
{
//add checkb to second array
[yourSecondArray addObject:[yourDictionary objectForKey:key]];
}
...
}
if contryArray is your dictionary then access it as follow
[contryArray valueForKey:#"checka0"];
and go on adding this values to another array
You can use the following code:
- (void)filterDictionary:(NSDictionary *)dict
{
NSArray *allKeys = [dict allKeys];
NSMutableArray *allValues = [[NSMutableArray alloc]init];
for(id key in allKeys)
{
id value = [dict valueForKey:key];
[allValues addObject:[value stringValue]];
}
}
I want to merge two NSDictionary in one NSDictionary.
my first DIctionary
BreakFast Dates Dic {
"2012-07-24" = "27";
"2012-08-03" = "98";
"2012-08-06" = "4203";
"2012-08-23" = "0";
"2012-08-24" = "0";
"2012-09-11" = "36";
"2012-09-19" = "450";
"2012-09-24" = "36";
Goals = 3;
}
my second Dictonary
Dinner Dates Dic {
"2012-08-03" = "100";
"2012-08-27" = "0";
"2012-09-19" = "270";
Goals = 4;
}
i want to merge both dictionary into one. like if in breakfast i have "2012-09-19" and same date i have in dinner. i want to separate both values by comma (,) .
my resultant dictionary should be like this.
combine {
"2012-07-24" = "27,0";
"2012-08-03" = "98,100";
"2012-08-06" = "4203,0";
"2012-08-23" = "0,0";
"2012-08-24" = "0,0";
"2012-09-11" = "36,0";
"2012-09-19" = "450,270";
"2012-09-24" = "36,0";
Goals = 3,4;
}
NSMutableDictionary *combined = [objectDelegate.dataBreakFastSummary mutableCopy];
for(NSString *key in [combined allKeys])
{
NSString *breakfastDate = [objectDelegate.dataBreakFastSummary valueForKey:key];
NSString *dinnerDate = [objectDelegate.dataDinnerSummary objectForKey:key];
if(dinnerDate){
[combined setObject:[NSString stringWithFormat:#"%#,%#",breakfastDate, dinnerDate] forKey:key];
} else {
[combined setObject:[NSString stringWithFormat:#"%#,0",breakfastDate] forKey:key];
}
}
NSLog(#"Combine %#",combined);
I did a query to the Flickr API and It returned me with an NSArray containing dictionaries. I was wondering how i might be able to access lets the _content item of the array that was sent back to me.
NSArray *topPlaces = [FlickrFetcher topPlaces];
NSLog(#"%#",topPlaces);
(
{
"_content" = "London, England, United Kingdom";
latitude = "51.506";
longitude = "-0.127";
"photo_count" = 3061;
"place_id" = "hP_s5s9VVr5Qcg";
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+Kingdom/England/London";
timezone = "Europe/London";
woeid = 44418;
},
{
"_content" = "New York, NY, United States";
latitude = "40.714";
longitude = "-74.007";
"photo_count" = 1886;
"place_id" = ".skCPTpTVr.Q3WKW";
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+States/New+York/New+York";
timezone = "America/New_York";
woeid = 2459115;
},
{
"_content" = "Weston-Super-Mare, England, United Kingdom";
latitude = "51.346";
longitude = "-2.977";
"photo_count" = 945;
"place_id" = HWdHmQdVUrptMA;
"place_type" = locality;
"place_type_id" = 7;
"place_url" = "/United+Kingdom/England/Weston-Super-Mare";
timezone = "Europe/London";
woeid = 40016;
},
)
Just iterate over the NSArray like so
for (NSDictionary *dictionary in topPlaces) {
NSLog(#"%#", [dictionary objectForKey:#"_content"]);
}
I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);
I am trying to read the following json object using the json-framework and obj-C
{
Sections = {
Now = "Wednesday 9 February 2011 02:40";
Section = (
{
Article = (
{
Exceprt = "text here";
ID = 49011;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = False;
likesCounter = 0;
photoCounter = 0;
time = "21:12";
timeStamp = "2/8/2011 9:14:16 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
},
{
Exceprt = "text here";
ID = 49010;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = True;
likesCounter = 0;
photoCounter = 0;
time = "20:45";
timeStamp = "2/8/2011 9:10:59 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
},
{
Exceprt = "text here";
ID = 49008;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = False;
likesCounter = 0;
photoCounter = 0;
time = "20:28";
timeStamp = "2/8/2011 9:09:44 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
}
);
ID = 22;
Name = "EN Live";
totalNews = 3416;
}
);
};
}
My intent is to have a list of the articles (list of dictionaries) so that I can later access them easily. I have been stuck a while on this and my code is giving me an error about calling a non existent method for NSArray which has led me to suspect that I am misunderstanding the json object. I am totally new to this and any help is greatly appreciated.
Here's my code:
NSDictionary *results = [jsonString JSONValue];
NSDictionary *Articles = [[results objectForKey:#"Sections"] objectForKey:#"Section"];
NSArray *ListOfArticles = [Articles objectForKey:#"Article"];
for (NSDictionary *article in ListOfArticles)
{
NSString *title = [article objectForKey:#"Title"];
NSLog(title);
}
Thanks !
First of all, those aren’t valid JSON data. Names (in name/value pairs) are strings and must be quoted. String values must always be quoted. Boolean values must be either true or false (lowercase). Check http://json.org/ and http://www.ietf.org/rfc/rfc4627.txt?number=4627 and http://jsonlint.com
Here’s the structure of your data:
The top level value is an object (dictionary)
This object has a name (key) called Sections whose value is itself another object (dictionary)
Sections has a name (key) called Section whose value is an array
Each element in the Section array is an object (dictionary)
Each element in the Section array has a name (key) called Article whose value is an array, as well as other names (keys): ID, title, totalNews
Each element in the Article array is an object
If your JSON data were valid, you could parse them as follows:
// 1.
NSDictionary *results = [jsonString JSONValue];
// 2.
NSDictionary *sections = [results objectForKey:#"Sections"];
// 3.
NSArray *sectionsArray = [sections objectForKey:#"Section"];
// 4.
for (NSDictionary *section in sectionsArray) {
// 5.
NSLog(#"Section ID = %#", [section objectForKey:#"ID"];
NSLog(#"Section Title = %#", [section objectForKey:#"Title"];
NSArray *articles = [section objectForKey:#"Article"];
// 6.
for (NSDictionary *article in articles) {
NSLog(#"Article ID = %#", [article objectForKey:#"ID"];
NSLog(#"Article Title = %#", [article objectForKey:#"Title"];
// …
}
}
Your JSON framework is probably parsing out an NSDictionary where you're expecting an NSArray. It'll let you assign an NSDictionary to an NSArray, but then you'll get a runtime exception when you attempt to call a method on your "array". Judging by the JSON you posted (which isn't correct JSON), this is what I would have my parsing code look like. The names of the NSDictionaries and NSArrays are simply named after the JSON attributes they represent.
NSDictionary* results = [jsonString JSONValue];
NSDictionary* sections = [results valueForKey:#"Sections"];
NSArray* section = [sections valueForKey:#"Section"];
NSArray article = [[section objectAtIndex:0] valueForKey:#"Article"];
for (NSDictionary* anArticle in article) {
NSLog(#"%#", [anArticle valueForKey:#"Title"]);
}