相关疑难解决方法(0)

使用Swift 4中的JSONDecoder,缺少的键可以使用默认值而不必是可选属性吗?

Swift 4添加了新Codable协议.当我使用JSONDecoder它似乎要求我的Codable类的所有非可选属性在JSON中有键或它会引发错误.

使我的类的每个属性都是可选的似乎是一个不必要的麻烦,因为我真正想要的是使用json中的值或默认值.(我不希望这个属性为零.)

有没有办法做到这一点?

class MyCodable: Codable {
    var name: String = "Default Appleseed"
}

func load(input: String) {
    do {
        if let data = input.data(using: .utf8) {
            let result = try JSONDecoder().decode(MyCodable.self, from: data)
            print("name: \(result.name)")
        }
    } catch  {
        print("error: \(error)")
        // `Error message: "Key not found when expecting non-optional type
        // String for coding key \"name\""`
    }
}

let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) …
Run Code Online (Sandbox Code Playgroud)

json swift swift4 codable

88
推荐指数
5
解决办法
3万
查看次数

iso8601使用swift4解码日期json

所以,我的json中有iso8601日期,看起来像"2016-06-07T17:20:00.000 + 02:00"

有没有办法使用swift4解析这些iso8601日期?我错过了一些明显的东西吗

我尝试了以下,但只有来自jsonShipA的dateString"2016-06-07T17:20:00Z"是可解析的....

import Foundation

struct Spaceship : Codable {
    var name: String
    var createdAt: Date
}

let jsonShipA = """
{
    "name": "Skyhopper",
    "createdAt": "2016-06-07T17:20:00Z"
}
"""

let jsonShipB = """
{
    "name": "Skyhopper",
    "createdAt": "2016-06-07T17:20:00.000+02:00"
}
"""

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

let dataA = jsonShipA.data(using: .utf8)!
if let decodedShip = try? decoder.decode(Spaceship.self, from: dataA) {
    print("jsonShipA date = \(decodedShip.createdAt)")
} else {
    print("Failed to decode iso8601 date format from jsonShipA")
}

let dataB …
Run Code Online (Sandbox Code Playgroud)

swift swift4

12
推荐指数
2
解决办法
7575
查看次数

标签 统计

swift ×2

swift4 ×2

codable ×1

json ×1