Objective-C字符串处理问题

问题描述 投票:2回答:3

我试图从JSON响应中读取类似下面的内容

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

使用SBJSON我设法获得'目标'字段,

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

当我做NSLOG时,它会显示www.google.com

但是这段代码对其他密钥对不起作用。

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

当我尝试打印testString时,它给了我一个错误。

在控制台我印刷的价值,他们是,

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

如何提取65和27?

objective-c json nsstring nsarray
3个回答
1
投票

这是一个对象数组。尝试:

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");
}

1
投票

做这个:

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);
}

键值1,2,3的逻辑重复相同


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

然后你的物品在[data objectAtIndex:0][data objectAtIndex:1]

© www.soinside.com 2019 - 2024. All rights reserved.