我正在尝试使用JSON格式的PHP打印MySQL结果集,并使用iOS读取它。
这是我的 JSON-string :
[{"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;
}
)
非常感谢您的帮助。
答案 0 :(得分:2)
有时内省在这里很有用。例如NSLog(@“字典的类型为:%@”,[字典类]);
我说的原因是基于你的输出,看起来字典实际上是一个包含两个NSDictionaries的数组。如果是这种情况,你会想要做这样的事情:
for (NSDictionary *actualDictionary in dictionary<this is really an array>)
{
NSString *myStringValue = [actualDictionary objectForKey:@"city"];
// etc...
}
你必须首先找出你实际处理的数据类型。
答案 1 :(得分:0)
这样做:
#import <objc/runtime.h>
NSLog(@"The class name is %s", object_getClassName(dictionary);
答案 2 :(得分: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"]);
......
}
}