ios开发——JSON解析

来源:互联网 发布:网络新歌2017伤感歌曲 编辑:程序博客网 时间:2024/05/30 05:06

ios开发JSON解析


解析经纬度
- (IBAction)buttonInsideOk:(id)sender {

    //得到请求地址,进行请求,返回JSON
    NSString *urlInput = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?address=%@&sensor=false",self.textJSONInput.text];
    NSURL *urlJSON = [NSURL URLWithString:urlInput];
    NSData *dataJSON = [NSData dataWithContentsOfURL:urlJSON];
   
    //解析JSON
    NSError *errorJSON = [[NSError alloc] init];
   id temp = [NSJSONSerialization JSONObjectWithData:dataJSON options:NSJSONReadingMutableContainers error:&errorJSON];
 
    Class classType = [temp class];

    if([classType isSubclassOfClass:[NSDictionary class]]){
        NSDictionary *dictJSON = (NSDictionary *)temp;
        NSArray *arrResult = [dictJSON objectForKey:@"results"];
        
        for(id single in arrResult){
            NSDictionary *tempArrResult = single;
         
            //取地址
            NSString *dictAddress = [tempArrResult objectForKey:@"formatted_address"];
            self.labAddress.text = dictAddress;


            //自定义地址显示格式
            NSArray *arrAddress = [tempArrResult objectForKey:@"address_components"];
            NSString *myAddress ;
            int dm_i = 0;
            for(id tempAd in arrAddress){
                NSDictionary *tempAddress = (NSDictionary *)tempAd;
                if(dm_i == 0){
                     NSString *myAppend = [NSString stringWithFormat:@"%@", [tempAddress objectForKey:@"long_name"]];
                     myAddress = myAppend;
                     dm_i += 1;
                }else{
                     NSString *myAppend = [NSString stringWithFormat:@"%@-%@", [tempAddress objectForKey:@"long_name"],myAddress];
                     myAddress = myAppend;
                }
            }
            self.textMyAddress.text = myAddress;
          
            //几何学,
            NSDictionary *tempDictArr = [tempArrResult objectForKey: @"geometry"];
                //地点,位置
            NSDictionary *dictGeometry = [tempDictArr objectForKey:@"location"];
                //取经度
            self.labOne.text = [NSString stringWithFormat:@"%@",[dictGeometry objectForKey:@"lng"]];
                //取纬度
            self.labTwo.text = [NSString stringWithFormat:@"%@",[dictGeometry objectForKey:@"lat"]];
        }
        
        NSLog(@"%@",dictJSON);
    }else if([classType isSubclassOfClass:[NSArray class]]){
        NSArray *arrJSON = (NSArray *)temp;
        
    }
   
    //提取有效数据,显示到UI上
  
}

0 0
原创粉丝点击