2017-04-07 94 views
0

我很难用Swift解析JSON。我写了一个函数,它向api发出get请求,并以JSON的形式检索数据并将其转换为字典。之后,我尝试使用tableViewController从我从JSON接收的值中设置每个标题和副标题。我试图设置标题作为主队和副标题作为客队。我对斯威夫特不太了解,所以我希望得到一些帮助。使用Swift词典解析JSON

这里是我的JSON存储在一个字典:

dictionary = ["scoreboard": { 
    gameScore =  (
       { 
      game =    { 
       ID = 35119; 
       awayTeam =     { 
        Abbreviation = ATL; 
        City = Atlanta; 
        ID = 91; 
        Name = Hawks; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = CLE; 
        City = Cleveland; 
        ID = 86; 
        Name = Cavaliers; 
       }; 
       location = "Quicken Loans Arena"; 
       time = "7:30PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35120; 
       awayTeam =     { 
        Abbreviation = MIA; 
        City = Miami; 
        ID = 92; 
        Name = Heat; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = TOR; 
        City = Toronto; 
        ID = 81; 
        Name = Raptors; 
       }; 
       location = "Air Canada Centre"; 
       time = "7:30PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35121; 
       awayTeam =     { 
        Abbreviation = NYK; 
        City = "New York"; 
        ID = 83; 
        Name = Knicks; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = MEM; 
        City = Memphis; 
        ID = 107; 
        Name = Grizzlies; 
       }; 
       location = "FedEx Forum"; 
       time = "8:00PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35122; 
       awayTeam =     { 
        Abbreviation = DET; 
        City = Detroit; 
        ID = 88; 
        Name = Pistons; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = HOU; 
        City = Houston; 
        ID = 109; 
        Name = Rockets; 
       }; 
       location = "Toyota Center"; 
       time = "8:00PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35123; 
       awayTeam =     { 
        Abbreviation = SAS; 
        City = "San Antonio"; 
        ID = 106; 
        Name = Spurs; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = DAL; 
        City = Dallas; 
        ID = 108; 
        Name = Mavericks; 
       }; 
       location = "American Airlines Center"; 
       time = "8:30PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35124; 
       awayTeam =     { 
        Abbreviation = NOP; 
        City = "New Orleans"; 
        ID = 110; 
        Name = Pelicans; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = DEN; 
        City = Denver; 
        ID = 99; 
        Name = Nuggets; 
       }; 
       location = "Pepsi Center"; 
       time = "9:00PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35125; 
       awayTeam =     { 
        Abbreviation = MIN; 
        City = Minnesota; 
        ID = 100; 
        Name = Timberwolves; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = UTA; 
        City = Utah; 
        ID = 98; 
        Name = Jazz; 
       }; 
       location = "Vivint Smart Home Arena"; 
       time = "9:00PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35126; 
       awayTeam =     { 
        Abbreviation = OKL; 
        City = "Oklahoma City"; 
        ID = 96; 
        Name = Thunder; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = PHX; 
        City = Phoenix; 
        ID = 104; 
        Name = Suns; 
       }; 
       location = "Talking Stick Resort Arena"; 
       time = "10:00PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     }, 
       { 
      game =    { 
       ID = 35127; 
       awayTeam =     { 
        Abbreviation = SAC; 
        City = Sacramento; 
        ID = 103; 
        Name = Kings; 
       }; 
       date = "2017-04-07"; 
       homeTeam =     { 
        Abbreviation = LAL; 
        City = "Los Angeles"; 
        ID = 105; 
        Name = Lakers; 
       }; 
       location = "Staples Center"; 
       time = "10:30PM"; 
      }; 
      isCompleted = false; 
      isInProgress = false; 
      isUnplayed = true; 
      quarterSummary = "<null>"; 
     } 
    ); 
    lastUpdatedOn = "<null>"; 
}] 

这里是我目前的设置我的标题和副标题在斯威夫特:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "NBAScore", for: indexPath) 

     // Configure the cell...     
     if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] 
     { 
      if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject] 
       { 
        if let game = gameScore["game"] as? [String:AnyObject] 
         { 
          if let awayTeam = game["awayTeam"] as? String 
           { 
            cell.textLabel?.text = awayTeam        } 
         } 
       } 
     } 
     return cell 
    } 
+1

你应该在JSON数据中深入挖掘的最后一个地方是'cellForRowAt'。在读取JSON数据后,建立一个适当的,简单的数据模型。然后使用这个简单的数据数组作为你的表视图的数据模型。 – rmaddy

回答

0

我能弄清楚我自己的问题的答案。字典的“gameScore”键给我带来了麻烦,因为我输错了它。这是一个数组< [字符串:任何]>不是一本字典。

func parseJSON(){ 
      var s = nbaScore() 
      var i = 0 
      if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] 
      { 
      // Could check the lastUpdattedOn date before doing the following: 
       if let gameScore = scoreBoard["gameScore"] as? Array<[String:Any]> 
       { //Loop for # of games 
        //while gameScore[i]["game"] as? [String:Any] != nil 
        while i < gameScore.count 
        //for _ in (gameScore[0]["game"] as? [String:Any])! 
        { 

        // An array of dictionaries 
         if let game = gameScore[i]["game"] as? [String:Any] 
          { 
           s.gameTime = (game["time"] as? String)! 

           if let awayTeam = game["awayTeam"] as? [String:Any] 
           { 
            s.awayTeamCity = (awayTeam["City"] as? String)! 
            s.awayTeamName = (awayTeam["Name"] as? String)! 
           } 
           if let homeTeam = game["homeTeam"] as? [String:Any] 
           { 
            s.homeTeamCity = (homeTeam["City"] as? String)! 
            s.homeTeamName = (homeTeam["Name"] as? String)! 
           } 

          } 
         if let isUnplayed = gameScore[i]["isUnplayed"] as? String 
         { 
          s.isUnplayed = isUnplayed 
         } 
         if let isInProgress = gameScore[i]["isInProgress"] as? String 
         { 
          s.isInProgress = isInProgress 
         } 
         if let isCompleted = gameScore[i]["isCompleted"] as? String 
         { 
          s.isCompleted = isCompleted 
         } 
         if let awayScore = gameScore[i]["awayScore"] as? String 
         { 
          s.awayTeamScore = awayScore 
         } 
         if let homeScore = gameScore[i]["homeScore"] as? String 
         { 
          s.homeTeamScore = homeScore 
         } 
         i += 1 
         scores.append(s) 
         s.clearData() 
         gamesCount += 1 
        } 
       } 
      } 
     } 
0

使用下面的代码来获得团队名称 -

if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] 
     { 
      if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject] 
       { 
        if let game = gameScore["game"] as? [String:AnyObject] 
         { 
          if let awayTeam = game["awayTeam"] as? [String: AnyObject] { 
            if let teamName = awayTeam["Name"] as? String { 
             cell.textLabel?.text = teamName 
            }        
           } 
         } 
       } 
     } 
+0

我没有工作。我无法通过第二个“如果让”声明。 –

+0

我又增加了一个答案。上面检查我的答案。你的gameScore对象是一个不是字典的数组。 –

0

最好将为您的属性创建一个Struct添加变量d之后,从该结构中创建一个数组,使用for循环解析您的json数组,然后将它们追加到您创建的新数组中,然后您可以在cellForRow函数内使用点符号访问这些属性

0

为此,使用一些构建的库来将JSON字典解析为某些模型对象,因为这是一种很好的做法。例如。我会推荐Marshal,因为它轻巧易用。

您只需创建一个结构或任何其他Swift结构,然后调用Marshal。稍后在tableView数据源中使用这些映射对象。

0

您的'gameScore'对象是一个不是字典类型的数组([String:AnyObject])。我的错误,我没有正确检查json对象。

首先创建一个数组并将所有团队名称存储在该数组中。例如,我现在将所有的离队名称存储在数组中。检查下面的代码。我没有在我的最后运行下面的源代码,因为你的JSON有问题。这不是有效的json数据。有格式问题。但是,下面的代码将起作用。

let awayTeamArr = NSMutableArray() 
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] { 
    if let gameScore = scoreBoard["gameScore"] as? NSArray { 

     for gameScoreObj in gameScore { 
      if let gameObj = gameScoreObj as [String: AnyObject] { 
       if let game = gameObj["game"] as? [String:AnyObject] { 
        if let awayTeam = game["awayTeam"] as? [String: AnyObject] { 
         if let teamName = awayTeam["Name"] as? String { 
          awayTeam.add(teamName) 
         } 
        } 
       } 
      } 
     } 
    } 
} 

然后在您的每个单元格的tableView委托方法中显示'awayTeamArr'对象的特定索引的对象。如果这个答案有效,那么问题就完成了。