ios - 如何使用 Swift 为 JSON 数据创建 JSON Codable 和 Decodable?
问题描述
在 myscenario 中,我试图在 Stuct Codable 和 Decodable 的帮助下从 JSON 响应中获取数据。但是如果我使用下面的代码,我会遇到错误
Error:typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
下面的代码
func jsonDataLoad() {
if let url = URL(string: "https://api.myjson.com/bins/1e33oo") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
//Swift 2/3/Objective C
//let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
//print(json)
let student = try JSONDecoder().decode(RootElement.self, from: data)
print(student.gender)
} catch let error {
print(error)
}
}
}.resume()
}
}
可编码结构
// MARK: - RootElement
struct RootElement: Decodable {
let id, name, gender, welcomeClass: String
let club, persona, crush, breastSize: String
let strength, hairstyle, color: String
let accessory, scheduleTime, scheduleDestination, scheduleAction: String
}
解决方案
你的 json root 是一个数组而不是字典[RootElement].self
let students = try JSONDecoder().decode([RootElement].self, from: data)
students.forEach {
print($0.id)
}
推荐阅读
- shell - 如何通过 github 工作流对 shell 脚本进行语法检查
- python - 将 json 的 url 解析为一个列表,其中包含来自 python 中特定 json 键的所有值
- tensorflow - 输出层中 Softmax 激活函数的输出计算值与实际值不匹配
- angular - 多用户应用程序附加多个帐户
- vb.net - 我可以在 Windows 服务(vb.net)中调用/执行 vb6 应用程序吗?
- python - Selenium python,使用css只选择两个类
- flutter - 如何与来自 Flutter integration_test 的原生 UI 元素进行交互?
- python-3.x - Azure 函数触发 http Azure 函数
- python - 如何在正确的 PyQt5 QLineEdit 中更新所选项目?
- javascript - javascript中的array.splice函数