json - 我需要使用 Alamofire 解析 Json 的帮助

标签 json swift parsing alamofire

我是一名初学者程序员,我无法解析我的 json 文件。我可以在控制台中看到数据,但我需要帮助来解析 json 数据。我分享了来自 url 的 json 数据,我想用 Alamofire 进行解析。我使用 Alamofite 和 SwiftyJSON 安装了 PodFile。我没有任何错误,但我需要帮助来解析它。 我还为以下数据创建了字符串数组。我将在数组中附加数据。

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

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?
}

最佳答案

您需要responseData才能使用JSONDecoder

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

此外,球员奖杯也是数组

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, type, quantity: String?
}

关于json - 我需要使用 Alamofire 解析 Json 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56756292/

相关文章:

android - GSON 返回异常 json 语法异常需要一个字符串,但在第 1 行第 15 列处是 begin_object

ios - 使用具有多个异步调用的调度队列

java - 不使用正则表达式识别电子邮件字段

SwiftUI - 如何使 NavigationView 不影响几何读取器的位置

java - 使用java解析json(simplejson)

c - C 中 JavaScript 非递归解析器的设计(高度内存受限)

javascript - 如果对象不存在,如何不破坏 JavaScript 代码?

json - 如何从 Redis 的 ServiceStack 实现返回的 Json Datetime 格式转换为 .net Datetime?

java - 为什么我的图像没有从 JSON 文件加载?

ios - 滑动图像数组时出现内存泄漏