Get objects of NSDictionary in to an array? [closed] - iphone

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a dictionary like :
{
levels = {
exchange = {
text = ALL;
};
product = {
text = ALL;
};
segment = {
text = ALL;
};
symbol = {
text = ALL;
};
};
marginavailable = {
adhocmargin = {
text = "0.00";
};
branchadhoc = {
text = "0.00";
};
cashmarginavailable = {
text = "0.00";
};
collateralvalue = {
text = "0.00";
};
credits = {
text = "0.00";
};
directcollateralvalue = {
text = "0.00";
};
notionalcash = {
text = 0;
};
payinamount = {
text = "0.00";
};
};
marginutilised = {
adhocscripmargin = {
text = "0.00";
};
category = {
text = 0;
};
cncmarginused = {
text = 0;
};
cncsellcreditpresent = {
text = 0;
};
debits = {
text = "0.00";
};
elm = {
text = "0.00";
};
exposuremargin = {
text = "0.00";
};
grossexposurevalue = {
text = "0.00";
};
ipoamount = {
text = "0.00";
};
mfamount = {
text = "0.00";
};
multiplier = {
text = "0.00";
};
payoutamount = {
text = "0.00";
};
premiumpresent = {
text = "0.00";
};
realisedmtom = {
text = "-0.00";
};
scripbasketmargin = {
text = "0.00";
};
spanmargin = {
text = "0.00";
};
subtotal = {
text = "0.00";
};
turnover = {
text = "0.00";
};
unrealisedmtom = {
text = "-0.00";
};
valueindelivery = {
text = "0.0";
};
varmargin = {
text = "0.00";
};
};
net = {
text = "0.00";
};
}
Above dictionary contains four keys that is levels,marginavailable,marginutilised and net etc
I want objects from first three keys and last object in to an array.I have tried a lot but not finding out any logic to parse it.
I want array of dictionary like this
exchange = {
text = ALL;
};
product = {
text = ALL;
};
segment = {
text = ALL;
};
symbol = {
text = ALL;
};
adhocmargin = {
text = "0.00";
};
branchadhoc = {
text = "0.00";
};
cashmarginavailable = {
text = "0.00";
};
collateralvalue = {
text = "0.00";
};
credits = {
text = "0.00";
};
directcollateralvalue = {
text = "0.00";
};
notionalcash = {
text = 0;
};
payinamount = {
text = "0.00";
};
adhocscripmargin = {
text = "0.00";
};
category = {
text = 0;
};
cncmarginused = {
text = 0;
};
cncsellcreditpresent = {
text = 0;
};
debits = {
text = "0.00";
};
elm = {
text = "0.00";
};
exposuremargin = {
text = "0.00";
};
grossexposurevalue = {
text = "0.00";
};
ipoamount = {
text = "0.00";
};
mfamount = {
text = "0.00";
};
multiplier = {
text = "0.00";
};
payoutamount = {
text = "0.00";
};
premiumpresent = {
text = "0.00";
};
realisedmtom = {
text = "-0.00";
};
scripbasketmargin = {
text = "0.00";
};
spanmargin = {
text = "0.00";
};
subtotal = {
text = "0.00";
};
turnover = {
text = "0.00";
};
unrealisedmtom = {
text = "-0.00";
};
valueindelivery = {
text = "0.0";
};
varmargin = {
text = "0.00";
};
net = {
text = "0.00";
};
thanks in advance.

You can use addEntriesFromDictionary: of NSMutableDictionary to build a new dictionary that merges each of the second-level dictionaries of your original data.
Something like this:
// Original data presumed held in origData
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[newDict addEntriesFromDictionary: [origData objectForKey: #"levels"]];
// etc. for the other keys

You just try following logic it may help you.
resultAry = [[NSMutableArray alloc]init];
[resultAry addObject:[[parentDictionary objectForKey:#"levels"]objectForKey:#"exchange"]];
Like that you add all object from levels key then follow the same way for marginavailable and marginutilised
Then finally add net
[resultAry addObject:[parentDictionary objectForKey:#"net"]];

This code should hold good if the maindictionary contains dictionaries
NSMutableArray *dictionaryArray = [[NSMutableArray alloc]init];
for (NSDictionary *childDictionaries in rootDict) { // rootDict is the original dictionary whic has all the four keys levels,marginAvailable,marginutilized and net
for (NSDictionary *dict in childDictionaries) {
[dictionaryArray addObject:dict];
}
}

NSMutableArray *newArray = [[NSMutableArray alloc]init];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
{
if ([(NSString *)key isEqualToString:#"marginutilised"])
*stop = YES;
[newArray addObjectsFromArray:(NSArray *)obj];
}];
Now you can got the result in newArray :)

To get all objects in a array, you can also use enumerateKeysAndObjectsUsingBlock: like so
NSMutableArray *yourArray = [NSMutableArray arrayWithCapacity:0];
[yourDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if([(NSString*)key isEqualToString:#"net"]){
[yourArray addObject:[(NSDictionary*)obj objectForKey:#"net"]];
*stop = YES;
}
[yourArray addObject:obj];
}];

Related

how to select image from JSON parsed in Array

I am using JSON parsing, I put data in array named JSON Array. In console it looks like
JSON Array=(
{
"created_by" = 42;
"created_on" = "2012-02-29 11:23:37";
"file_description" = "";
"file_is_downloadable" = 0;
"file_is_forSale" = 0;
"file_is_product_image" = 1;
"file_meta" = "";
"file_mimetype" = "image/jpeg";
"file_params" = "";
"file_title" = "hand shovel";
"file_type" = product;
"file_url" = "images/stories/virtuemart/product/cca3cd5db813ee6badf6a3598832f2fc.jpg";
"file_url_thumb" = "images/stories/virtuemart/product/resized/cca3cd5db813ee6badf6a3598832f2fc_90x90.jpg";
"locked_by" = 0;
"locked_on" = "0000-00-00 00:00:00";
"modified_by" = 42;
"modified_on" = "2012-02-29 11:23:37";
ordering = 0;
"product_name" = "Hand Shovel";
published = 0;
shared = 0;
"virtuemart_category_id" = 1;
"virtuemart_media_id" = 13;
"virtuemart_product_id" = 1;
"virtuemart_vendor_id" = 1;
},
{
"created_by" = 42;
"created_on" = "2012-02-29 11:35:09";
"file_description" = "";
"file_is_downloadable" = 0;
"file_is_forSale" = 0;
"file_is_product_image" = 1;
"file_meta" = "";
"file_mimetype" = "image/jpeg";
"file_params" = "";
"file_title" = "our ladder";
"file_type" = product;
"file_url" = "images/stories/virtuemart/product/8cb8d644ef299639b7eab25829d13dbc.jpg";
"file_url_thumb" = "images/stories/virtuemart/product/resized/8cb8d644ef299639b7eab25829d13dbc_90x90.jpg";
"locked_by" = 0;
"locked_on" = "0000-00-00 00:00:00";
"modified_by" = 42;
"modified_on" = "2012-02-29 11:35:09";
ordering = 0;
"product_name" = Ladder;
published = 0;
shared = 0;
"virtuemart_category_id" = 3;
"virtuemart_media_id" = 8;
"virtuemart_product_id" = 2;
"virtuemart_vendor_id" = 1;
},
Now from this i need to select "file_url_thumb" which is actually image in seperate array.
please let me know how can i do this?
//Your array has two dictionary ..
for(NSMutableDictionary *dict in JSON_Array){
NSString *urlString = [dict objectForKey:#"file_url_thumb"];
if(urlString){
NSURL *url = [NSURL urlWithString:urlString];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:url]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
//show your image on imageview
}
}
Hope this will help you
NSString *str_URL =[ [json objectAtIndex:anIndex] valueForKey:#"file_url_thumb"];
NSString *urlString = [[jsonArray objectAtIndex:0] objectForKey:#"file_url_thumb"];
This will give you value for "file_url_thumb" as a string.

Multidimensional array issues

I am creating a multidimensional array for sections / rows based on json data from our API. Looking at the logs the adding rows and sections look good but when I nslog the sections it only shows a bunch of the last object. It seems like the rows are not being added to sections.
What am I doing wrong to make the last API object show in the sections x times? x represents the json count. self.appointments is an NSArray *
According to objective-c multi-dimensional array it should work.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *sections = [[NSMutableArray alloc] init];
NSMutableArray *rows = [[NSMutableArray alloc] init];
NSString *lastDate = nil;
for (NSDictionary *dict in [json objectForKey:#"data"]) {
NSString *date = [dict objectForKey:#"date"];
NSLog(#"Dates: %# - %#", date, lastDate);
if (date != lastDate) {
if (lastDate == nil) {
NSLog(#"Adding Row 1");
[rows addObject:dict];
lastDate = date;
} else {
NSLog(#"Adding Section 1");
NSLog(#"Adding #rows %i",[rows count]);
[sections addObject:rows];
[rows removeAllObjects];
NSLog(#"Adding Row 2 %#",[dict objectForKey:#"start_time"]);
[rows addObject:dict];
lastDate = date;
}
} else {
NSLog(#"Adding Row 3");
[rows addObject:dict];
}
}
if (rows) {
NSLog(#"Adding Section 2");
NSLog(#"Adding #rows %i",[rows count]);
[sections addObject:rows];
}
NSLog(#"Sections: %#", sections);
self.appointments = [sections mutableCopy]; //I have also tried self.appointments = sections
sections = nil;
rows = nil;
Logs show
Sections: (
(
{
abbrev = "";
account = "";
"addOnService_id" = "";
alert = "";
"appt_id" = 1839384;
"appt_id_unique" = 1839384;
"appt_status_description" = "";
"appt_status_type" = "";
"c_id" = 47;
cost = "0.00";
"coupon_id" = "";
"creation_emp_id" = 2288;
"creation_timestamp" = 201111040717;
"customer_id" = 0;
"customer_notes" = "";
"customer_package_id" = "";
date = 20121228;
"employee_id" = 2288;
"employee_notes" = "";
employer = "";
"end_time" = 570;
"first_name" = "";
"history_id" = 1830959;
key = 134;
"last_emp_id" = 2288;
"last_name" = "";
"last_timestamp" = 201111040717;
"lead_description" = "";
"link_id" = 0;
"location_name" = "Telephonic Setup/Training";
"make_id" = "";
"middle_name" = "";
"model_id" = "";
"model_year" = "";
name = "My Name ";
odometer = "";
"other_vehicle" = "";
"package_name" = "";
"payment_type_description" = "";
"payment_type_id" = "";
"pet_id" = "";
"po_number" = "";
reason = "B.O.B";
"rebook_id" = "";
"recur_id" = 20954;
"rep_id" = "";
"room_id" = 0;
"room_name" = "";
service = "";
"service_id" = 0;
"service_time_description" = "";
spots = 1;
"staff_screen_name" = "John Smith";
"staff_type_id" = 0;
"start_time" = 540;
"status_id" = 0;
tip = "";
"type_id" = 8;
vin = "";
}
),
(
{
abbrev = "";
account = "";
"addOnService_id" = "";
alert = "";
"appt_id" = 1839384;
"appt_id_unique" = 1839384;
"appt_status_description" = "";
"appt_status_type" = "";
"c_id" = 47;
cost = "0.00";
"coupon_id" = "";
"creation_emp_id" = 2288;
"creation_timestamp" = 201111040717;
"customer_id" = 0;
"customer_notes" = "";
"customer_package_id" = "";
date = 20121228;
"employee_id" = 2288;
"employee_notes" = "";
employer = "";
"end_time" = 570;
"first_name" = "";
"history_id" = 1830959;
key = 134;
"last_emp_id" = 2288;
"last_name" = "";
"last_timestamp" = 201111040717;
"lead_description" = "";
"link_id" = 0;
"location_name" = "Telephonic Setup/Training";
"make_id" = "";
"middle_name" = "";
"model_id" = "";
"model_year" = "";
name = "My Name ";
odometer = "";
"other_vehicle" = "";
"package_name" = "";
"payment_type_description" = "";
"payment_type_id" = "";
"pet_id" = "";
"po_number" = "";
reason = "B.O.B";
"rebook_id" = "";
"recur_id" = 20954;
"rep_id" = "";
"room_id" = 0;
"room_name" = "";
service = "";
"service_id" = 0;
"service_time_description" = "";
spots = 1;
"staff_screen_name" = "John Smith";
"staff_type_id" = 0;
"start_time" = 540;
"status_id" = 0;
tip = "";
"type_id" = 8;
vin = "";
}
), ... over and over again.
With:
[sections addObject:rows];
[rows removeAllObjects];
[rows addObject:dict];
you keep adding the same rows object not a new one and keep changing the contents so the last contents display each time.
Try:
[sections addObject:[rows mutableCopy]];
[rows removeAllObjects];
[rows addObject:dict];
That way a new row is added each time.
Perhaps better yet:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *sections = [NSMutableArray array];
NSMutableArray *rows = [NSMutableArray array];
NSString *lastDate = nil;
for (NSDictionary *dict in [json objectForKey:#"data"]) {
NSString *date = [dict objectForKey:#"date"];
if ([date isEqualToString:lastDate] == NO) {
if (lastDate == nil) {
[rows addObject:dict];
lastDate = date;
} else {
[sections addObject:rows];
rows = [NSMutableArray array];
[rows addObject:dict];
lastDate = date;
}
[rows addObject:dict];
}
}
if (rows) {
[sections addObject:rows];
}
self.appointments = sections;
Note that assigning 0 to an object does not release it, release does. But if you use convenience methods to create objects then they are autoreleased and no further action is necessary to release them.
Also note that when comparing strings one needs to use the isEqualToString: method to compare the contents, just using the = or != only compares the address of the strings.

converting nsdictionary to xml format in iphone

I'am able to display the data in nsdictionary using this code
NSString *testXMLString = #"<items><item id=\"0001\" type=\"donut\"><name>Cake</name><ppu>0.55</ppu><batters><batter id=\"1001\">Regular</batter><batter id=\"1002\">Chocolate</batter><batter id=\"1003\">Blueberry</batter></batters><topping id=\"5001\">None</topping><topping id=\"5002\">Glazed</topping><topping id=\"5005\">Sugar</topping></item></items>";
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
NSLog(#"%#", xmlDictionary);
and the output is
items = {
item = {
batters = {
batter = (
{
id = 1001;
text = Regular;
},
{
id = 1002;
text = Chocolate;
},
{
id = 1003;
text = Blueberry;
}
);
};
id = 0001;
name = {
text = Cake;
};
ppu = {
text = "0.55";
};
topping = (
{
id = 5001;
text = None;
},
{
id = 5002;
text = Glazed;
},
{
id = 5005;
text = Sugar;
}
);
type = donut;
};
}; }
Can anyone please help me how to convert this dictionary into a xml file?
The NSPropertyListSerialization class should be able to do this for you.

How do I properly populate the UITableView NSArray from a NSDictionary created using JSONKit?

Sorry for the long question but that best summarizes what I am trying to do:
My JSON Looks like:
{
4e8cf1d6c7e24c063e000000 = {
"_id" = {
"$id" = 4e8cf1d6c7e24c063e000000;
};
author = faisal;
comments = (
{
author = adias;
comment = amazing;
},
{
author = nike;
comment = "I concur";
}
);
created = {
sec = 1317772800;
usec = 0;
};
text = "This is a random post";
title = "post # 1";
type = (
punjabi
);
};
4e91fd49c7e24cda74000000 = {
"_id" = {
"$id" = 4e91fd49c7e24cda74000000;
};
author = draper;
comments = (
{
author = adias;
comment = "amazing again";
}
);
created = {
sec = 1318118400;
usec = 0;
};
text = "This is a random post again";
title = "post # 2";
type = (
punjabi
);
};
}
What I would like to do is to ultimately have a UTTableview with each row having a title (text from above JSON):
This is the code I have so far:
NSString *responseString = [request responseString];
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
How do I put everything in an array for the UITableView? Again I am just a little rusty as I can swear I have done that before.
If you don't need the keys then you can convert it to an array by using allValues, e.g.:
NSArray *values = [resultsDictionary allValues];
Does your JSON really parse to an NSDictionary, or is this an NSArray containing NSDictionary instances? If the latter, then isn't it just something like:
NSString *textForCell = [[resultsArray objectAtIndex:row] valueForKey:#"title"];

Loop through NSDictionary to create separate NSArrays

I have a large NSDictionary that I need to loop through and create separate NSArrays. Here are the contents:
(
{
id = {
text = "";
};
sub = {
text = " , ";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2010-2011";
};
type = {
text = "title";
};
},
{
id = {
text = "76773";
};
sub = {
text = "December 13, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
};
title = {
text = "College Days - Fall 2010";
};
type = {
text = "gallery";
};
},
{
id = {
text = "";
};
sub = {
text = "";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2009-2010";
};
type = {
text = "title";
};
},
{
id = {
text = "76302";
};
sub = {
text = "December 3, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
};
title = {
text = "Christmas Colloquy";
};
type = {
text = "gallery";
};
}
)
Each section has a type key, which I need to check. When it finds the title key, I need to add those to an array. Then the next sections that would use the gallery key needs to be in its own array until it finds another title key. Then the gallery keys after that into their own array.
I am using a UITableView section titles and content. So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.
I have tried using a for loop but I just can't seem to get it right. Any ideas would be appreciated.
It's somewhat unclear by your log, but I'm guessing your NSDictionary has values of NSDictionary? If so:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:#"type"] == #"title")
[titles addObject:[subDictionary objectForKey:#"title"]];
// etc.
}
Your question is a bit unclear... but this is how you would properly loop through an NSDictionary.
EDIT:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:#"type"];
if (type == #"title") {
currentTitle = [subDictionary objectForKey:#"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == #"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
After this loop, galleries will contain keys of type NSString (with values of the titles), and corresponding objects of type NSArray (with values of the gallery NSDictionarys). Hopefully this is what you were going for.
NSString *key;
for(key in someDictionary){
NSLog(#"Key: %#, Value %#", key, [someDictionary objectForKey: key]);
}
Modern Objective-C syntax:
NSMutableArray *things = [NSMutableArray array];
NSMutableArray *stuff = [NSMutableArray array];
NSMutableArray *bits = [NSMutableArray array];
[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[things addObject:[obj valueForKeyPath:#"thing"]];
[stuff addObject:[obj valueForKeyPath:#"enclosing_object.stuff"]];
[bits addObject:[obj valueForKeyPath:#"bits"]];
}];