• ios 解析json,xml


    一、发送用户名和密码给服务器(走HTTP协议)


        // 创建一个URL : 请求路径
        NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText, pwdText];
        NSURL *url = [NSURL URLWithString:urlStr];
        
        // 创建一个请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSLog(@"begin---");
        
        // 发送一个同步请求(在主线程发送请求)
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        // 解析服务器返回的JSON数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *error = dict[@"error"];
        if (error) {
            // {"error":"用户名不存在"}
            // {"error":"密码不正确"}
            [MBProgressHUD showError:error];
        } else {
            // {"success":"登录成功"}
            NSString *success = dict[@"success"];
            [MBProgressHUD showSuccess:success];
        }

     
    二、加载服务器最新的视频信息json
        // 1.创建URL
        NSURL *url = HMUrl(@"video");
        
        // 2.创建请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 3.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError || data == nil) {
                [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
                return;
            }
            
            // 解析JSON数据
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *videoArray = dict[@"videos"];
            for (NSDictionary *videoDict in videoArray) {
                HMVideo *video = [HMVideo videoWithDict:videoDict];
                [self.videos addObject:video];
            }
            
            // 刷新表格
            [self.tableView reloadData];
        }];


    三、 加载服务器最新的视频信息XML

        
        // 1.创建URL
        NSURL *url = HMUrl(@"video?type=XML");
        
        // 2.创建请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 3.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError || data == nil) {
                [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
                return;
            }
            
            // 解析XML数据
            
            // 加载整个XML数据
            GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
            
            // 获得文档的根元素 -- videos元素
            GDataXMLElement *root = doc.rootElement;
            
            // 获得根元素里面的所有video元素
            NSArray *elements = [root elementsForName:@"video"];
            
            // 遍历所有的video元素
            for (GDataXMLElement *videoElement in elements) {
                HMVideo *video = [[HMVideo alloc] init];
                
                // 取出元素的属性
                video.id = [videoElement attributeForName:@"id"].stringValue.intValue;
                video.length = [videoElement attributeForName:@"length"].stringValue.intValue;
                video.name = [videoElement attributeForName:@"name"].stringValue;
                video.image = [videoElement attributeForName:@"image"].stringValue;
                video.url = [videoElement attributeForName:@"url"].stringValue;
                
                // 添加到数组中
                [self.videos addObject:video];
            }
            
            // 刷新表格
            [self.tableView reloadData];
        }];

    四、XML

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        /**
         加载服务器最新的视频信息
         */
        
        // 1.创建URL
        NSURL *url = HMUrl(@"video?type=XML");
        
        // 2.创建请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 3.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError || data == nil) {
                [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
                return;
            }
            
            // 解析XML数据
            
            // 1.创建XML解析器 -- SAX -- 逐个元素往下解析
            NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
            
            // 2.设置代理
            parser.delegate = self;
            
            // 3.开始解析(同步执行)
            [parser parse];
            
            // 4.刷新表格
            [self.tableView reloadData];
        }];
    }

    #pragma mark - NSXMLParser的代理方法
    /**
     *  解析到文档的开头时会调用
     */
    - (void)parserDidStartDocument:(NSXMLParser *)parser
    {
    //    NSLog(@"parserDidStartDocument----");
    }

    /**
     *  解析到一个元素的开始就会调用
     *
     *  @param elementName   元素名称
     *  @param attributeDict 属性字典
     */
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
    {
        if ([@"videos" isEqualToString:elementName]) return;
        
        HMVideo *video = [HMVideo videoWithDict:attributeDict];
        [self.videos addObject:video];
    }

    /**
     *  解析到一个元素的结束就会调用
     *
     *  @param elementName   元素名称
     */
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
    //    NSLog(@"didEndElement----%@", elementName);
    }

    /**
     *  解析到文档的结尾时会调用(解析结束)
     */
    - (void)parserDidEndDocument:(NSXMLParser *)parser
    {
    //    NSLog(@"parserDidEndDocument----");
    }

    #pragma mark - Table view data source
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.videos.count;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *ID = @"video";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        }
        
        HMVideo *video = self.videos[indexPath.row];
        
        cell.textLabel.text = video.name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"时长 : %d 分钟", video.length];
        
        // 显示视频截图
        NSURL *url = HMUrl(video.image);
        [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placehoder"]];
        
        return cell;
    }

     
  • 相关阅读:
    漫谈LiteOS-端云互通组件-MQTT开发指南(下)
    漫谈LiteOS-端云互通组件-MQTT开发指南(上)
    漫谈LiteOS之开发板-LiteOS移植(基于GD32450i-EVAL)
    漫谈LiteOS-Huawei_IoT_Link_SDK_OTA 开发指导
    SpringBoot 2.3 整合最新版 ShardingJdbc + Druid + MyBatis 实现分库分表
    从零开始实现放置游戏(十五)——实现战斗挂机(6)在线打怪练级
    Windows系统安装最新版本RabbitMQ3.8.3报错解决
    从零开始实现放置游戏(十四)——实现战斗挂机(5)地图移动和聊天
    从零开始实现放置游戏(十二)——实现战斗挂机(3)数据字典和缓存改造
    从零开始实现放置游戏(十一)——实现战斗挂机(2)注册登陆和游戏主界面
  • 原文地址:https://www.cnblogs.com/zhongxuan/p/4856259.html
Copyright © 2020-2023  润新知