通过JSON获取联赛信息

let url = "http://op.juhe.cn/onebox/football/league?key=API_KEY=%e8%8b%b1%e8%b6%85"   //api接口
do{
    //1. 将接口url包装成NSRUL
    //2. 将NSURL的内容读取下载,存放到NSData对象,也就是jsonData
    let jsonData = NSData(contentsOf: NSURL(string: url)  as! URL)
    
    
    //使用JSONSerialization将NSData的数据解析成JSON格式 (如果我们的 JSON 根节点是以对象形式存放的,那么我们得到的就是一个 NSDictionary。而如果是以数组形式存放的,那么我们得到的就是一个 NSArray 了。)
    let json = try JSONSerialization.jsonObject(with: jsonData as! Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as? NSDictionary
    //print(json)
    
    
    let league_result = json?["result"] as? NSDictionary
    let league_name = league_result?["key"] as! String //获取接口对应的联赛名字
    let league_tabs = league_result?["tabs"] as? NSDictionary  //获取轮次,积分榜等信息
    let league_views = league_result?["views"] as? NSDictionary
    
    //射手榜
    let league_sheshoubang = league_views!["sheshoubang"] as! NSArray  //射手榜内容
    for i in 0...9 {
        let sheshoubangindex = league_sheshoubang[i] as! NSDictionary
        let sheshou_name = sheshoubangindex["c2"]!  //射手榜球员名字
        let sheshou_team = sheshoubangindex["c3"]!  //射手榜球员所在球队
    }
    
    //积分榜
    let league_jifenbang = league_views!["jifenbang"] as! NSArray
    for i in 0...9{
        let jifenbangindex = league_jifenbang[0] as! NSDictionary
        let jifen_name = jifenbangindex["c2"]!
    }

    //本轮比赛信息
    let league_saicheng1 = league_views!["saicheng1"] as! NSArray
    for i in 0...9 {
        let saichengname = league_saicheng1[i] as! NSDictionary
        let saichengzhu = saichengname["c4T1"]!
        let saichengke = saichengname["c4T2"]!
        let saichengdate = saichengname["c2"]!
        let saichengtime = saichengname["c3"]!
    }
    
    //下轮比赛信息
    let league_saicheng2 = league_views!["saicheng2"] as! NSArray
    for i in 0...9 {
        let saichengname = league_saicheng2[i] as! NSDictionary
        let saichengzhu = saichengname["c4T1"]!
        let saichengke = saichengname["c4T2"]!
        let saichengdate = saichengname["c2"]!
        let saichengtime = saichengname["c3"]!
    }
    
 
}  catch {
    NSLog("JSON解析失败")
}

你可能感兴趣的:(通过JSON获取联赛信息)