如何在字符串数组中附加Json值?

时间:2019-06-25 16:54:51

标签: arrays json parsing swift5

我正在用Alamofire和SwiftyJSON解析Json。我可以从网址看到所有json数据。控制台中的所有内容都很清楚,但是我需要在字符串数组中附加一些值。如您所见,json值。我创建了3个字符串数组。我需要在队伍,球员名称和奖杯后面附加数组。我将在表格视图中列出球队和球员的姓名。我需要帮助将值追加到数组中

//控制台中的json值

[
  {
    "id" : 1,
    "team" : "Liverpool",
    "players" : [
      {
        "id" : 2,
        "name" : "Alisson",
        "position" : "Goal Keeper",
        "number" : "13"
      },
      {
        "id" : 3,
        "name" : "Salah",
        "position" : "Forward",
        "number" : "10"
      }
    ],
    "trophies" : [
      "2019 champions league",
      "2005 champions league"
    ],
    "logoUrl" : "url"
  },
  {
    "id" : 4,
    "team" : "Real Madrid",
    "players" : [
      {
        "id" : 5,
        "name" : "Ramos",
        "position" : "Defender",
        "number" : "4"
      },
      {
        "id" : 6,
        "name" : "Benzema",
        "position" : "Forward",
        "number" : "9"
      }
    ],
    "trophies" : [
      "2018 champions league",
      "2017 champions league",
      "2016 champions league"
    ],
    "logoUrl" : "url"
  }
]


import Alamofire
import SwiftyJSON

var team = [String]()
var playerName = [String]()
var trophies = [String]()

func fetchJsonData(){
       DispatchQueue.main.async {
            Alamofire.request(url).responseData { response in
            guard let data = response.data else { return }
            do {
                let res = try JSONDecoder().decode([PageData].self, from:data)
                print(res)
            } catch  {
                print("having trouble converting it to a dictionary" , error)
            }
        }

        }
}

// this is my modal file

struct PageData: Codable { 
    let team: String?
    let players: [Player]
    let trophies: [String]
    let logoUrlL: String?
}

struct Player: Codable {
    let id: Int 
    let name,position, number: String?
}

2 个答案:

答案 0 :(得分:0)

首先使res可变

var res = try JSONDecoder().decode([PageData].self, from:data)

将球员添加到利物浦

if let index = res.firstIndex(where: { $0.name == "Liverpool"}) {
   res[index].players.append(Player(id: 7, name: "Virgil van Dijk", position: "Defender", number: "4"))
}

为皇马增添奖杯

if let index = res.firstIndex(where: { $0.name == "Real Madrid"}) {
   res[index].trophies.append("None in 2019")
}

添加团队

res.append(PageData(team: "Paris Saint-Germain", 
                    players: [Player(id: 8, name: "Neymar Jr.", position: "Forward", number: "10")], 
                    trophies: ["Ligue 1 2019"]))

根据您的代码,您不使用SwiftyJSON

答案 1 :(得分:0)

您需要做

1-声明一个像这样的数组

var arr = [PageData]()

2-在此处分配并重新加载

arr = try JSONDecoder().decode([PageData].self, from:data)
self.tableView.reloadData()

3-设置数据源和委托

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CellName
    let item = arr[indexPath.row]
    cell.teamlbl.text = item.team
    cell.playerslbl.text = item.players.map{ $0.name}.joined(separator:"-")
    cell.trophieslbl.text = item.trophies.joined(separator:"-")
    return cell
}

编辑:

  var teams = [String]()
  var players = [Player]()
  var trophies = [String]()


  arr = try JSONDecoder().decode([PageData].self, from:data)
  self.teams = arr.compactMap { $0.team }
  self.players = arr.flatMap { $0.players }.compactMap { $0.name }
  self.trophies = arr.flatMap { $0.trophies } 
  self.tableView.reloadData()