handle JSON response in project - iphone

I am a new programmer. I get the following response from server. How can i get the value of 0 index "Mile High Motors of Butte" and "Mile High Motors of Dillion" from following
Thanks
{
dealer = (
{
0 = "Mile High Motors of Butte";
1 = "3883 Harrison";
2 = Butte;
3 = 59701;
4 = MT;
5 = "http://www.buttesmilehighchryslerjeepdodge.com";
6 = 2;
7 = 0;
address = "3883 Harrison";
city = Butte;
distance = 0;
id = 2;
name = "Mile High Motors of Butte";
state = MT;
url = "http://www.buttesmilehighchryslerjeepdodge.com";
zip = 59701;
},
{
0 = "Mile High Motors of Dillon";
1 = "790 N Montana St";
2 = Dillon;
3 = 59725;
4 = Montana;
5 = "http://www.MileHighDillon.com";
6 = 13;
7 = "60.1235269593172";
address = "790 N Montana St";
city = Dillon;
distance = "60.1235269593172";
id = 13;
name = "Mile High Motors of Dillon";
state = Montana;
url = "http://www.MileHighDillon.com";
zip = 59725;
}
);
success = 1;
}

Okay let's see your structure (assuming that you have already deserialized your JSON string).
You have an NSDictionary with two keys (dealer & success). Now dealer key is an NSArray with two NSDictionaries. So based on that we could do:
NSDictionary *myJson; // Assuming that this is what you have posted
NSArray *dealers = [myJson valueForKey:#"dealer"];
// Now just grab whatever you need
NSString *dealerOne = [[dealers objectAtIndex:0] valueForKey:#"0"]; //Mile High Motors of Butte
NSString *dealerTwo = [[dealers objectAtIndex:1] valueForKey:#"0"]; //Mile High Motors of Dillon
Or you could just iterate your dealers array like this:
for (NSDictionary *dealer in dealers)
{
NSString *dealerName = [dealer valueForKey:#"0"];
// Do something useful
}

NSMutableArray yourStringArray= [[NSMutableArray alloc] init]; //for getting texts what you want.
NSArray * array1 = [yourDictionary valueForKey:#"dealer"];// You will get array which has dictionary elements.
for (NSDictionary *dealer in array1)// Write loop for getting your string.
{
NSString *dealerName = [dealer valueForKey:#"0"];
[yourStringArray addObject:dealerName];
}
I think it will be helpful to you.

Related

Objective C : Get correct float values(justified)

I worked a lot in it and can't find a solution. Even the title can't explain clearly.
I have three values weight, quantity and total
I had done the following
float wq = [[weightarray objectAtIndex:selectedint]floatValue];
float q = [quantity floatValue];
float total = wq * q;
for ex, if
[weightarray objectAtIndex:selectedint] = #"3.14";
quantity = 4;
then the result is
wq = 3.140000 q= 4.000000 total = 12.560000
but I need
wq = 3.14 total = 12.56
what to do?
I searched a lot, someone suggests to use NSDecimal,
NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE];
but the scale is not 2 here, wq value may have 3 or four numbers after point.
If the total = 2.30000100 means I need total = 2.300001
how to solve this?
I'm not entirely sure what it is your asking for, but it seems as if you want the values to only display a 2 d.p. In which case you could use a string format like so:
NSString *output = [NSString stringWithFormat:#"float = %.2f", 3.14];
The .2 specifies that the float should be justified to 2 d.p.
Hope this helps
There may be a more direct way to achieve it (which I don't know) but here's a suggestion...
Convert to string as you already do.
Use [myString hasSuffix:#"0"] to see if it ends in zero.
Use [myString substringToindex:[myString length]-1] to create a new string without the final zero.
Repeat.
I know it's not elegant, but unless someone has a better solution, this will at least do what you want.
UPDATE: scratch that - I just discovered [myString stringByTrimmingCharactersInSet:set]. Surely this must be what you need...?
Finally solution found, thanks to Martin
float total = 12.56000;
NSString *s = [NSString stringWithFormat:#"%f", total];
NSLog(#"%#",s);
BOOL success;
success =NO;
while(!success)
{
if ([s hasSuffix:#"0"])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
}
else if ([s hasSuffix:#"."])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
success = YES;
}
else
success = YES;
}
NSLog(#"%#",s);
if total = 12.560000 it returns total = 12.56
if total = 12.000000 it returns total = 12
if total = 10.000000 it returns total = 10
if total = 12.3000100 it returns total = 12.30001

How retrireve array from dictionary

I have 2 columns in my Sqlite table 1.DetailsID & 2.Detailstype
i have stored values id: int and detailstype :varchar.
set the id with string in sqlite select query as
while(sqlite3_step(selectPrefer) == SQLITE_ROW)
{
NSString *detailsString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectPrefer, 1)];
int detailsId = (int)sqlite3_column_int(selectPrefer, 0);
[detailsData setObject:detailsString forKey:[NSNumber numberWithInt:detailsId ]];
}
I have a NSmutable dictionary like this:
(
0 = "˚F";
12 = Activity;
11 = BM;
7 = "Heart Rate";
6 = "Nose Problem";
2 = Rx;
1 = BP;
10 = Food;
9 = "Stress Level";
8 = Glucose;
5 = "Pain Level";
4 = Weight;
3 = Events;
}
i can get arrays using allKeys & allValues but these are not in order
Now i want seperate arrays like
{
0
1
2
3
4
5
6
7
8
9
10
11
12
)
both values & keys In ascending order with respect to keys
(
"˚F";
Activity;
BM;
"Heart Rate";
"Nose Problem";
Rx;
BP;
Food;
"Stress Level";
Glucose;
"Pain Level";
Weight;
Events;
)
with out any modifications in sqlite query
- what to do thannks in advance
You should use the allKeys and allValues property of the dictionay :
allKeys Returns a new array containing the dictionary’s keys.
allValues Returns a new array containing the dictionary’s values.
Try this :
NSArray *keysArray = [yourDictionnay allKeys];
NSArray *valuesArray = [yourDictionnay allvalues];
Hope this helps,
Vincent
you need both allValues and allkeys.
NSArray *values = [dictionary allValues];
NSArray *keys = [dicitoary allKeys];

Format a String in IPhone

I need to add space after every 4 characters in a string.. For example if the string is aaaaaaaa, i need to format it as aaaa aaaa. I tried the following code, but it doesn't work for me.
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:#" " atIndex:i];
}
}
Can anyone help me with this?
You haven't said what isn't working with your code, so it's hard to know exactly what to answer. As a tip - in future questions don't just say "it isn't working", but state WHAT isn't working and HOW it isn't working. However...
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:#" " atIndex:i];
}
}
You are inserting a space, but you are not then accounting for this in your index value. So, suppose your formattedString is aaaaaaaaaaaaaaaa
The first time through your loop, you will get to the 4th position and insert a space at i=4
aaaa aaaaaaaaaaaa
Now the next time you get to insert a space, i will be 8. But the 8th position in your currentFormattedString isn't where you think it will be
aaaa aaa aaaaaaaaa
Next time it will be another 4 characters along which still isn't where you think
aaaa aaa aa aaaaaaa
And so on
You have to take into account the inserted space which will affect the offset value.
NSString *text = [[NSString alloc] initWithString:#"aaaaaaaa"];
NSString *result = [[NSString alloc] init];
double count = text.length/4;
if (count>1) {
for (int i = 0; i<count; i++) {
result = [NSString stringWithFormat:#"%#%# ",result,[text substringWithRange:NSMakeRange(i*4, 4)]];
}
result = [NSString stringWithFormat:#"%#%# ",result,[text substringWithRange:NSMakeRange(((int)count)*4, text.length-((int)count)*4)]];
}
else result = text;
I found the following which formats a string to a telephone number format, but it looks like you could easily change it to support other formats
Telephone number string formatting
Nick Bull answered on the reasons why your method broke already.
IMHO the appropriate solution would be to use a while loop and do the loop increments yourself.
NSInteger i = 4; // first #" " should be inserted after the 4th (index = 3) char
while (i < count) {
[currentFormattedString insertString:#" " atIndex:i];
count ++; // you did insert #" " so the length of the string increased
i += 5; // you now must skip 5 (" 1234") characters
}

Sorting NSMutableArray?

I want to be sort NSMutableArray and its structure is something like that,
Object1:NSMutableDictionary
Affiliation = 2165;
CallLetters = abc;
Channel = "2.1";
ChannelLocation = "";
ChannelSchedules = (
);
DisplayName = abc;
DvbTriplets = (
);
FullName = "bc";
IconAvailable = 1;
Order = 1;
ParentNetworkId = 2;
ServiceType = Digital;
SourceAttributeTypes =
HD
SourceId = 11222;
SourceType = Broadcast;
TiVoSupported = 1;
Type = "24-Hours";
Object2:NSMutableDictionary
Affiliation = 1209;
CallLetters = "xyz";
Chann?el = "4.1";
ChannelLocation = "";
ChannelSchedules = (
);
DisplayName = "xyz";
DvbTriplets = (
);
FullName = "xyz";
IconAvailable = 1;
Order = 2;
ParentNetworkId = 5;
ServiceType = Digital;
SourceAttributeTypes = HD
SourceId = 111
SourceType = Broadcast;
TiVoSupported = 1;
Type = "24-Hours";
VirtualChannelNumber = "4.1";
...
..
.
.
.
./
The array contains many objects, and those objects contain many dictionaries. I want to be able to arrange the above array in ascending order using the NSMutableDictionary key "Channel" ?
How can I sort the array?
Use NSSortDescriptor it will work
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Channel" ascending:YES];
[yourarrayobject sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
[aSortDescriptor release];
To sort your array of objects you:
setup NSSortDescriptor - use names of your variables as keys to
setup descriptor for sorting plus the selector to be executed on
those keys
get the array of descriptors using NSSortDescriptor that you've
setup
sort your array based on those descriptors
How to sort NSMutableArray using sortedArrayUsingDescriptors?

Array index is always 0, can't get it to iterate through the array in a forloop. Using in MapView

I have an array that I want to show on a mapvew, the forloop iterates fine but the index of thew array is always 0.
self.clientTable = [ClientDatabase database].clientTable;
ClientTable *info = nil;
[_nameLabel setText:info.name];
[_stateLabel setText:info.state];
int countArray = [self.clientTable count];
for (int i=0;i<countArray;i++) {
info.uniqueId=i;
NSLog(#" i = %d ; id = %d",i, info.uniqueId);
}
however the results are always
24
i = 0 ; id = 0
i = 1 ; id = 0
i = 2 ; id = 0
i = 3 ; id = 0
i = 4 ; id = 0
i = 5 ; id = 0
I know the array has data as it displays in the tableview fine.
Any ideas?
The reason for the above is displaying each item in a mapview.
Thankyou!
Before this line
info.uniqueId=i;
are you missing something like
info = [self.clientTable objectAtIndex:i]
?? In the code you've provided you set info to nil, but never to anything else.
Because you set info to nil, right up there.