How can I append Json values in sting arrays?

拟墨画扇 提交于 2019-12-24 07:34:28

问题


I am parsing Json with Alamofire and SwiftyJSON. I can see all json data from url. Everything is clear in my console but I need to append some values in string arrays. As you can see json values. I create 3 string arrays. I need to append to arrays teams, player names and trophies. I will list team and player name in tableview. I need help to append values in arrays

// json values in console

[
  {
    "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?
}

回答1:


First make res mutable

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

Add a player to Liverpool

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

Add a trophy to Real Madrid

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

Add a team

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

And according to your code you don't use SwiftyJSON




回答2:


You need to do

1- Declare an array like

var arr = [PageData]()

2- Assign here and reload

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

3- Set dataSource and delegate

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
}

Edit:

  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()


来源:https://stackoverflow.com/questions/56758760/how-can-i-append-json-values-in-sting-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!