gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:41:14 25 4
gpt4 key购买 nike

我是一名初学者程序员,我无法解析我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com