简体   繁体   English

如何在iOS中解析复杂的JSON数据

[英]how to Parse complicated JSON data in iOS

I am using php to get json data and here is response. 我正在使用php获取json数据,这是响应。

{"array":[{"Category":{"charity_id":"2","charity_name":"GiveDirectly","charity_amt":"0.20"}}]}

and here is my Objective-c code 这是我的Objective-c代码

NSError *err;
NSURL *url=[NSURL URLWithString:@"url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];

if ([json isKindOfClass:[NSDictionary class]]){ 
    NSArray *yourStaffDictionaryArray = json[@"array"];
    if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
        for (NSDictionary *dictionary in yourStaffDictionaryArray) {

            for(NSDictionary *dict in dictionary[@"Category"]){

                NSLog(@"%@",[[((NSString*)dict) componentsSeparatedByString:@"="] objectAtIndex:0] );


            }

        }
    }
}

But this only returns the name's not the value. 但这仅返回名称而不是值。 I have searched most of the question on this site but nothing helped be. 我已经在该网站上搜索了大多数问题,但没有任何帮助。 Please help me i am new to iOS. 请帮助我,我是iOS的新手。

Thanks 谢谢

Dictionary output is 字典输出为

{
"charity_amt" = "0.20";
"charity_id" = 2;
"charity_name" = GiveDirectly;
}

You don't need to do ComponentSeparatedByString. 您无需执行ComponentSeparatedByString。 Once you get the NSDictionary for @"Category", you can get its value by using its keys. 一旦获得@“ Category”的NSDictionary,就可以使用其键获取其值。

Something like 就像是

if ([json isKindOfClass:[NSDictionary class]]){
    NSArray *yourStaffDictionaryArray = json[@"array"];
    if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
        for (NSDictionary *dictionary in yourStaffDictionaryArray) {

            NSDictionary *dict = dictionary[@"Category"];
            NSLog(@"%@",dict[@"charity_id"]);
        }
    }
}

Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array 永远记住,当有{}大括号时,表示它是字典,而当[]这时,则表示数组

NSURL *url=[NSURL URLWithString:@"Your JSON URL"];

NSData *data = [[NSData alloc] initWithContentsOfURL:url];

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSArray *array = json[@"array"];

for(NSMutableDictionary *dic in array)
{
  NSLog(@"%@",dic[@"Category"][@"charity_id"]); // prints 2
  NSLog(@"%@",dic[@"Category"][@"charity_name"]); // GiveDirectly
  NSLog(@"%@",dic[@"Category"][@"charity_amt"]); // 0.20
}

this is my parser json data, it's demo 这是我的解析器json数据,它是演示

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *urlString         = @"https://api.foursquare.com/v2/venues/search?categoryId=4bf58dd8d48988d1e0931735&client_id=TZM5LRSRF1QKX1M2PK13SLZXRXITT2GNMB1NN34ZE3PVTJKT&client_secret=250PUUO4N5P0ARWUJTN2KHSW5L31ZGFDITAUNFWVB5Q4WJWY&ll=37.33%2C-122.03&v=20140118";
    NSURL   *url                = [NSURL URLWithString:urlString];
    NSURLRequest *request       = [NSURLRequest requestWithURL:url];
//    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    NSOperationQueue *queue     = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                           NSString *string = [[NSString alloc] initWithData:data
                                                                                    encoding:NSUTF8StringEncoding];
                                           [self parser:data];
                                       }];
}


- (void)parser:(NSData *)data
{
    NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:0
                                                                       error:nil];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [obj enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        }];
    }];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM