Swift Playground中没有输出的JSONDecoder

时间:2019-03-17 21:11:26

标签: json swift swift-playground jsondecoder

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

1 个答案:

答案 0 :(得分:0)

userNamezipCode属性是驼峰式的,因为它们应该遵循Swift标准。但是,正如JSON数据经常发生的那样,键"username""zipcode"都以小写形式显示。幸运的是,有一个简单的解决方法。在您的private enums中,只需将两个properties都设置为小写stringValue,如下所示:

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

从技术上讲,我认为您处理nested dictionary中的JSON properties。不过,我不确定,也许该网站上的一些专家可以对此进行详细说明。