Rukshan
Rukshan

Reputation: 8066

Objective-C String handling issue

I'm trying to read from a JSON response something like below

{ 
"URL": 
  { 
     "target": "www.google.com", 
    "0": [ 92, 15 ], 
    "1": [ 92, 16 ], 
    "2": [ 74, 15 ], 
    "4": [ 5, 16 ] 
  } 
}

Using SBJSON I've managed to get 'target' field,

testString = [[result objectForKey:@"URL"] objectForKey:@"target"];

when I do a NSLOG it shows www.google.com

but this piece of code doesn't work for other key pairs.

testString = [[result objectForKey:@"URL"] objectForKey:@"0"];

and when I try to print testString it gives me an error.

In console I printed values, they were,

(lldb) po testString
(NSString *) $4 = 0x0864b190 <__NSArrayM 0x864b190>(
65,
27
)

How do I extract these 65 and 27 ?

Upvotes: 2

Views: 1002

Answers (3)

mprivat
mprivat

Reputation: 21902

NSArray *data = [[result objectForKey:@"URL"] objectForKey:@"0"];

Then your items are in [data objectAtIndex:0] and [data objectAtIndex:1]

Upvotes: 0

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Do this:

if([result objectForKey:@"URL"] objectForKey:@"0"] isKindofClass:[NSArray class])
{
   NSArray *arritems = [[result objectForKey:@"URL"] objectForKey:@"0"];
   NSMutableArray *values = [NSMutableArray array];
   for( id *item in arritems)
   {
      if([item is isKindOfClass:[NSString class]])
      {
         NSString * valueStr = item; 
         [values addObject:valueStr];
       }
      else if([item is isKindOfClass:[NSDecimalNumber class]])
      {
        NSDecimalNumber * valueNum = item; 
        [values addObject:valueNum];
       }
   } 
   NSLog(@"%@",values);
}

Same logic repeat for keys value 1 , 2 , 3

Upvotes: 1

justin
justin

Reputation: 104698

that is an array of objects. try:

NSArray * array = [[result objectForKey:@"URL"] objectForKey:@"0"];
id a = [array objectAtIndex:0]; // 65
id b = [array objectAtIndex:1]; // 27

// now determine the type of objects in the array, and use them appropriately:
if ([a isKindOfClass:[NSString class]]) {
  NSString * string = a;
  ...use appropriately
}
else if ([a isKindOfClass:[NSDecimalNumber class]]) {
  NSDecimalNumber * number = a;
  ...use appropriately
}
...
else {
  assert(0 && "type not supported");
}

Upvotes: 1

Related Questions