gpt4 book ai didi

arrays - 如何在 Swift 4 中选择要反序列化的 JSON 数组

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

JSON 链接:https://apps.runescape.com/runemetrics/profile/profile?user=Rhidlor

所以基本上我正在使用的 JSON 文件中有 2 个数组,我只想从第二个数组中获取信息。我的问题是如何指定要解码到各自结构中的数组,现在我认为我的代码只是试图解码它遇到的第一个数组,这是有问题的。

(“技能”结构是给我带来问题的结构)

import UIKit

struct User: Decodable {
var rank: String?
var totalxp: Int?
var totalskill: Int?
var combatlevel: Int?
var questscomplete: Int?

init(json: [String: Any]){
self.rank = json["rank"] as? String
self.totalxp = json["totalxp"] as? Int
self.totalskill = json["totalskill"] as? Int
self.combatlevel = json["combatlevel"] as? Int
self.questscomplete = json["questscomplete"] as? Int
}
//self.rank = rank
}

struct Skill: Decodable {
var level: Int?
var xp: Int?
var rank: Int?
var id: Int?

init(json: [String: Any]){
self.level = json["level"] as? Int
self.xp = json["xp"] as? Int
self.rank = json["rank"] as? Int
self.id = json["id"] as? Int
}

}

class ViewController: UIViewController {

@IBOutlet var greetingLabel: UILabel!
@IBOutlet var rankLabel: UILabel!
@IBOutlet var totalxpLabel: UILabel!
@IBOutlet var totalskillLabel: UILabel!
@IBOutlet var combatlevelLabel: UILabel!
@IBOutlet var questscompleteLabel: UILabel!

var username: String?

@IBAction func usernameTextField(_ sender: UITextField) {
username = sender.text!
parseJson(username: username!)
}

override func viewDidLoad() {
super.viewDidLoad()

}

func setValues(rank: String, totalxp: Int, totalskill: Int, combatlevel: Int, questscomplete: Int){
print("setValues fired")
greetingLabel.text = "Hello \(String(describing: username!))"
rankLabel.text = "Rank: \(rank)"
totalxpLabel.text = "Total Xp: \(totalxp)"
totalskillLabel.text = "Total Level: \(totalskill)"
combatlevelLabel.text = "Combat Level: \(combatlevel)"
questscompleteLabel.text = "Quests Complete: \(questscomplete)"
}

func parseJson(username: String){
let jsonUrlString = "https://apps.runescape.com/runemetrics/profile/profile?user=" + username
guard let url = URL(string: jsonUrlString) else {
print("guard let url failed")
return }

print(jsonUrlString)
var user: User!
var skills = [Skill]()
print("This fired")

URLSession.shared.dataTask(with: url) { (data, response, error) in
print("This also fired")

guard let data = data else {
print("guard let data failed")
return
}

print("This too fired")

do {
print("do fired")
user = try JSONDecoder().decode(User.self, from: data)
skills = try JSONDecoder().decode([Skill].self, from: data)
for eachSkill in skills {
//print("\(eachSkill.id) \(eachSkill.level)")
}
if user.rank != nil {
print("User values", user.rank!, user.totalxp!, user.totalskill!, user.combatlevel!, user.questscomplete!)
DispatchQueue.main.async {
self.setValues(rank: user.rank!, totalxp: user.totalxp!, totalskill: user.totalskill!, combatlevel: user.combatlevel!, questscomplete: user.questscomplete!)
}
} else {
let alert = UIAlertController(title: "Invalid Name", message: "The name you specified could not be found", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
catch let jsonError {
print("Error serializing json: ", jsonError)
}

}.resume()

}

}

最佳答案

仅当您从根对象开始解码所有(您需要的)一次时,隐式解码才有效。

此结构声明可对 UserSkill 进行解码。由于 API 似乎发送所有属性的值,因此无需使用选项。

struct User: Decodable {

private enum CodingKeys: String, CodingKey {
case rank, totalxp, totalskill, combatlevel, questscomplete
case skills = "skillvalues"
}

var rank: String
var totalxp: Int
var totalskill: Int
var combatlevel: Int
var questscomplete: Int

var skills : [Skill]
}

struct Skill: Decodable {
var level: Int
var xp: Int
var rank: Int
var id: Int
}

然后使用一个解码线:

user = try JSONDecoder().decode(User.self, from: data)
skills = user.skills

如果您只需要 skills 部分,请将 User 声明为

struct User: Decodable {

private enum CodingKeys: String, CodingKey {
case skills = "skillvalues"
}

var skills : [Skill]
}

关于arrays - 如何在 Swift 4 中选择要反序列化的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967065/

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