gpt4 book ai didi

Swift Playground 中没有输出的 JSONDecoder

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

我是 Swift JSON 新手,所以我正在 Swift Playgrounds 中练习。我非常确定这将被视为解码嵌套的 JSON 键。但就像我说的,我是新人,我并不熟悉所有技术术语。

无论如何,我认为这段代码是正确的,但由于某种原因它不会打印。而且它没有向我显示任何错误,这使得修复变得更加困难。但是,我一定做错了什么。

import UIKit

let jsonData :Data = """
{
"id": 1,
"name": "John Smith",
"username": "Johnny",
"email": "Johnny@yahoo.com",
"address": {
"street": "Some Street",
"suite": "100",
"city": "SomeCity",
"zipcode": "12345",
}
}

""".data(using: .utf8)!

struct User :Decodable {

let id :Int
let name :String
let userName :String
let email :String

let street :String
let suite :String
let city :String
let zipCode :String

private enum UserKeys :String, CodingKey {
case id
case name
case userName
case email
case address
}

private enum AddressKeys :String, CodingKey {

case street
case suite
case city
case zipCode

}

init(from decoder :Decoder) throws {

let userContainer = try decoder.container(keyedBy: UserKeys.self)

self.id = try userContainer.decode(Int.self, forKey: .id)
self.name = try userContainer.decode(String.self, forKey: .name)
self.userName = try userContainer.decode(String.self, forKey: .userName)
self.email = try userContainer.decode(String.self, forKey: .email)

let addressContainer = try userContainer.nestedContainer(keyedBy: AddressKeys.self, forKey: .address)

self.street = try addressContainer.decode(String.self, forKey: .street)
self.suite = try addressContainer.decode(String.self, forKey: .suite)
self.city = try addressContainer.decode(String.self, forKey: .city)
self.zipCode = try addressContainer.decode(String.self, forKey: .zipCode)

}

}

if let user = try? JSONDecoder().decode(User.self, from: jsonData) {
print(user.name)
print(user.city)
}

最佳答案

userNamezipCode 属性是驼峰式大小写,因为它们应该遵循 Swift 标准。但是,正如 JSON 数据经常发生的情况一样,键 "username""zipcode" 均以小写形式呈现。幸运的是,有一个简单的解决办法。在您的私有(private)枚举中,只需将两个属性设置为其小写的stringValue,如下所示:

 case userName = "username"
case zipCode = "zipcode"

从技术上讲,我认为您处理的是 JSON 属性嵌套字典。但我不确定,也许这个网站上的一些专家可以对此进行更详细的阐述。

关于Swift Playground 中没有输出的 JSONDecoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55211971/

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