Objective-C: NSDictionary and looping through inner NSDictionaries - iphone

I get the following NSDictionary when I parse a JSON response from my server:
(
{
fromUname = Ben;
id = ci2n9awef7tm7e142sx;
message = hi;
read = 1;
subject = hi;
time = 1316513972;
toUname = Jill;
},
{
fromUname = Eamorr;
id = asdf98s14u7tm7e142sx;
message = asdf;
read = 0;
subject = asdf;
time = 1316513322;
toUname = Jack;
}
)
I'm really struggling to extract the two subjects.
Here's what I've coded sofar (incomplete...):
...
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSLog(#"%#",obj);
NSLog(#"%d",[obj count]);
for(int i=0;i<[obj count];i++){
NSDictionary *message=[obj objectForKey:];
NSLog(#"%#",[message objectForKey:#"subject"]); //I'm stuck...
}
...
Can anyone give me some efficient way of extracting the subjects?
Many thanks in advance,

Its actually an NSArray of NSDictionaries. So to get the information, loop through the array and get the dictionary:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *obj = [parser objectWithString:[request responseString] error:nil];
NSLog(#"%# : %d",obj, [obj count]);
for (NSDictionary *dict in obj) {
NSLog(#"%#", [dict objectForKey:#"subject"]);
}

Related

Ios NSDictionary array - grouping values and keys

I have the following result of NSDictionary of Array
Bath = {
Keynsham = (
"nsham companies"
);
};
Bath = {
"Midsomer Norton" = (
"Keynsham companies"
);
};
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
};
Birmingham = {
"Acock's Green" = (
"Acock's Green taxi companies"
);
};
Birmingham = {
"Alcester Lane's End" = (
"Alcester Lane's End taxi companies"
);
};
How can i combine the values and keys so that I end up with only one category as shown below;
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
"Midsomer Norton" = (
"Keynsham companies"
);
Keynsham = (
"nsham companies"
);
};
I am not sure if this is the best way to explain it
the code is as follows
//all Nssarrays allocated/ initialised
NSURL *url=[NSURL URLWithString:#"http://y.php"];
NSData *data= [NSData dataWithContentsOfURL:url];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//instantiate arrays to hold data
NSMutableDictionary *dictArray=[[NSMutableDictionary alloc]init];
NSArray *cityName=[[NSArray alloc]init];
NSArray *townName=[[NSArray alloc]init];
NSArray *taxis=[[NSArray alloc]init];
NSArray *ids=[[NSArray alloc]init];
for (int i=0; i<json.count; i++)
{
//cityName=[[NSMutableArray alloc] initWithCapacity:json.count];
ids = [[json objectAtIndex:i] objectForKey:#"id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName=[[json objectAtIndex:i] objectForKey:#"townName"];
taxis=[[json objectAtIndex:i] objectForKey:#"taxis"];
NSMutableArray *taxisArray=[[NSMutableArray alloc] initWithObjects:taxis,nil];
NSMutableDictionary *towensdict=[[ NSMutableDictionary alloc] initWithObjectsAndKeys:taxisArray,townName, nil];
NSMutableDictionary *cities1=[[NSMutableDictionary alloc] initWithObjectsAndKeys:towensdict,cityName, nil];
NSLOG (#"%#", cities1) here, gives me the print out above
[dictArray addEntriesFromDictionary:cities1 ];
Then I tried Jdodgers solution as follows;
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
NSLog(#"%#", currentDictionary);
}
}
//this gives error "unrecognized selector sent to instance", here is the print out
combinedDictionary NSMutableDictionary * 0x000000010012e580
currentDictionary NSDictionary *const 0x0000000100116460
dictArray NSMutableDictionary * 0x000000010012e220
[0] key/value pair
key id 0x0000000100116460
[0] id
value id 0x000000010012e440
[0] id
keys NSArray * 0x0000000000000000
You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys.
For example, if your array was called dictArray, you could do:
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
}
}
This code first creates a dictionary combinedDictionary that will be your final dictionary. It loops through all of the dictionaries in your array and for each one does the following:
First, it gets an array of all keys in the dictionary. For the dictionaries you provided this array will look like #[#"Bath"] for the first 3 and #[#"Birmingam"] for the other two.
The code then loops through these keys and gets the already existing dictionary from the combined dictionary from this key. If the dictionary doesn't exist, one is created.
Then, it adds all of the values from the dictionary from the array and sets the new dictionary to be the one in combinedDictionary.

Convert Dictionaries into one array

This code:
for (NSDictionary *object in JSONArray) {
NSMutableArray *birdtemp = [[NSMutableArray alloc] initWithObjects:object[#"case_name"], nil];
[allparts addObject:birdtemp];
}
outputs this log:
log: (
(
"NZXT Phantom 410"
),
(
"Thermaltake MK+"
)
)
I want to know what code I could use to make that log into one array like:
log: (
"NZXT Phantom 410",
"Thermaltake MK+"
)
Json Array is:
log: (
{
"case_color" = White;
"case_description" = "";
"case_image" = "http://sitecom/get/parts/part_images/nzxtphantom410.jpeg";
"case_name" = "NZXT Phantom 410";
"case_price" = "99.99";
"case_type" = ATX;
id = 1;
},
{
"case_color" = Black;
"case_description" = "";
"case_image" = "http://site.com/get/parts/part_images/thernaltake-mkplus.jpeg";
"case_name" = "Thermaltake MK+";
"case_price" = "84.99";
"case_type" = ATX;
id = 2;
}
)
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSDictionary *dict in JSONArray) {
[array addObject:[dict objectForKey:#"case_name"]];
}
NSLog(#"Your Array: %#",array);
I think it will be helpful to you.
A simple way to obtain the result you are looking for is to use key-value coding (KVC):
NSArray *allparts = [JSONArray valueForKey:#"case_name"];
Key-value coding used on arrays in this way may seem a bit counter-intuitive at first, but it is very powerful.
Troubleshooted and got this:
allparts = [[NSMutableArray alloc] init];
NSString *birdtemp;
for (NSDictionary *object in JSONArray) {
birdtemp = object[#"case_name"];
[allparts addObject:birdtemp];
}
NSMutableArray *birdtemp = [NSMutableArray ....];
for (NSDictionary *object in JSONArray) {
[birdtemp addObject:object[#"case_name"]];
}
[allparts addObject:birdtemp];

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

How can i Parse xml data using GDataXML parser in iPhone application development?

-<stat>
<visitor>4</visitor>
<uniqueVisitor>2</uniqueVisitor>
<order>41</order>
<revenue>20658</revenue>
<conversionRate>48</conversionRate>
<newProduct>25</newProduct>
<outOfStockProduct>11</outOfStockProduct>
</stat>
From this xml i want to get the element name "visitor" & "uniqueVisitor" and their corresponding values using GDataXML parser.
Till now i have done these.
xmlFileLocation = [NSURL URLWithString:#"someurl....abc.php"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfURL:xmlFileLocation];
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
if (nil == xmlDocument) {
NSLog(#"could not load Branch.xml file");
}
else {
NSLog(#"Loading desire xml url for dashboard");
[self GDataXmlParser];
}
Using a tutorial i have done this till now. But now i want all of these element name and their corresponding values
-(void)GDataXmlParser{
NSArray *getData = [[xmlDocument rootElement]elementsForName:#"stat"];
records = [[NSMutableArray alloc]init];
tempArray = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in getData){
// What i have to do here????
}
}
look at the answer
NSLog(#"%#", xmlDocument.rootElement);
records = [[NSMutableArray alloc] init];
NSLog(#"Enering in the xml file");
NSString *Visitor = [[[xmlDocument.rootElement elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[xmlDocument.rootElement elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
for more see the link I am not able to parse xml data using GDataXML
Follow this link for tutorial :http://iphonebyradix.blogspot.com/2011/03/using-gdata-to-parse-xml-file.html
-(void) GDataXmlParser
{
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData
options:0
error:nil];
NSArray *temp = [xmlDocument.rootElement elementsForName:#"stat"];
NSMutableArray *records = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in temp)
{
[records addObject:e];
NSString *Visitor = [[[e elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[e elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
}
}
Hope it helps you. Happy iCoding.

key values from an NSDictionary formatting with "()"

I'm trying to pull two values from this Dictionary, But the values I'm getting have "()" around them. Any Ideas what is causing this?
Here is the ServerOutput:
{"Rows":[{"userid":"1","location":"beach"}]}
Dictionary after JSON:
{
Rows = (
{
location = beach;
userid = 1;
}
);
}
This is what I'm getting:
location : (
beach
)
user Id : (
1
)
Both the userid and the location key values have the "()". Here is the code. Thanks a lot.
NSString *serverOutput= [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if(serverOutput > 1){
SBJSON *jsonFF = [[SBJSON new] autorelease];
NSError *error3 = nil;
NSDictionary *useridDict= [jsonFF objectWithString:serverOutput error:&error3];
NSLog(#"useridDict: %#",useridDict);
idreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"userid"];
locationreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"location"];
NSLog(#" user Id : %#", idreturn);
NSLog(#" location : %#", locationreturn);
Just to clarify what is going on. When parsing JSON {} gets returned as a dictionary and [] gets retured as an array. So we have useridDict an NSDictionary containing the parsed data.
'useridDict' has one key Rows which returns an NSArray.
NSArray *useridArray = [useridDict objectForKey:#"Rows"];
Our useridArray has one element, an NSDictionary
NSDictionary *dict = [useridArray objectAtIndex:0];
This dict contains the two keys: location and userid
NSString *location = [dict objectForKey:#"location"];
NSInteger userid = [[dict objectForKey:#"userid"] intValue];
You can use like this.
idreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0]valueForKey:#"userid"];
locationreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0] valueForKey:#"location"];