1

我正在尝试使用 JSON 格式的 PHP 打印 MySQL 结果集,并使用 iOS 读取它。

这是我的JSON 字符串

[{"partnerid":"1","code":"SUMU6003","partnerName":"Company name","street":"Some Street 5323","zipCode":"8732","city":"Berlin","languages":"English","workers":"Name 1, Name 2","lineup":"Kids"},{"partnerid":"2","code":"DEMO8884","partnerName":"Partner 2","street":"Third street 2","zipCode":"383838","city":"Berlin","languages":"Greek","workers":"Petra","lineup":"Kids"}]

在这种方法中,我得到NSDictionary

#pragma mark - ServiceConnectorDelegate -

-(void)requestReturnedData:(NSData *)data { 
    NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
    # process dictionary and grep strings from json-string
    # ...
}

你能告诉我如何在循环中访问不同的结果集吗?我想分别访问每个键。

我知道NSDictionary包含数据,因为NSLog(@"%@",dictionary);打印:

2012-12-20 19:13:20.661 myapp[576:907] (
        {
        city = Berlin;
        code = SUMU6003;
        languages = English;
        lineup = Kids;
        partnerName = "Company name";
        partnerid = 1;
        street = "Some Street 5323";
        workers = "Name 1, Name 2";
        zipCode = 8732;
    },
        {
        city = Berlin;
        code = DEMO8884;
        languages = Greek;
        lineup = Kids;
        partnerName = "Partner 2";
        partnerid = 2;
        street = "Third street 2";
        workers = Petra;
        zipCode = 383838;
    }
)

非常感谢你的帮助。

4

3 回答 3

2

有时内省在这里很有用。例如 NSLog(@"dictionary is of type: %@", [dictionary class]);

我之所以这么说是基于您的输出,看来字典实​​际上是一个包含两个 NSDictionaries 的数组。如果是这种情况,你会想要做这样的事情:

for (NSDictionary *actualDictionary in dictionary<this is really an array>)
{
  NSString *myStringValue = [actualDictionary objectForKey:@"city"];
  // etc...
}

不过,您必须首先找出您实际处理的数据类型。

于 2012-12-20T18:22:03.613 回答
0

做这个:

#import <objc/runtime.h>

NSLog(@"The class name is %s", object_getClassName(dictionary);

于 2012-12-20T18:23:36.540 回答
0

您拥有的响应字典包含字典数组,因此您可以通过快速枚举字典来运行字典值并将每个字典转换为字典并获取其值,如下所示:

-(void)requestReturnedData:(NSData *)data { 
    NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
    # process dictionary and grep strings from json-string
    for(id item in dictionary ) 
    {
        NSDictionary *dic = (NSDictionary *)item;
        NSLog(@"%@",[dic objectForKey:@"city"]);
        NSLog(@"%@",[dic objectForKey:@"code"]);
        ......
    }
 }
于 2012-12-20T20:46:00.227 回答