我已经开始将一些JSON解析代码转换为使用新的Apple Decodable协议(protocol),并且遇到了一个阻止程序,该阻止程序感觉太基本了,无法在Apple测试期间错过,因此我想知道自己是否在做一些愚蠢的事情。
简而言之,我正在尝试解析这样的JSON图,由于我只是解码,所以我认为符合Decodable应该足够了,但是从错误看来,我需要符合Codable(Decodable&Encodable)才能获得所需的结果解码效果:

{"keyString": {"nestedKey1" : "value1", "nestedKey1" : "value1" } }

它适用于这种情况:
{"keyString": [{"nestedKey1" : "value1", "nestedKey1" : "value1" } ]}

就像嵌套对象的数组一样,而不是单个对象。

这是Swift的错误,还是我出了点问题?

这是一个可以证明问题的示例游乐场。如果Animal类符合Decodable,则不会针对数组大小写进行解析,但是如果我将Animal设置为符合Codable,则它将起作用。我不希望出现这种情况,因为我在这里仅解码JSON。
import Foundation

//class Animal: Codable {
class Animal: Decodable {
    var fileURLPath: String = ""
    var age: Double = 0
    var height: Double = 0
    var weight: Double = 0

    private enum CodingKeys: String, CodingKey {
        case fileURLPath = "path"
        case age
        case height
        case weight
    }

    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        fileURLPath = try values.decode(String.self, forKey: .fileURLPath)
        age = try values.decode(TimeInterval.self, forKey: .age)
        height = try values.decode(Double.self, forKey: .height)
        weight = try values.decode(Double.self, forKey: .weight)
    }
}

let innerObjectJSON = """
{
    "path": "tiger_pic.png",
    "age": 9,
    "height": 1.23,
    "weight": 130
}
"""

let innerObjectData = innerObjectJSON.data(using: String.Encoding.utf8)

let jsonDataNestedObject = """
    { "en" : \(innerObjectJSON)
    }
    """.data(using: String.Encoding.utf8)

let jsonDataNestedArray = """
    { "en" : [\(innerObjectJSON), \(innerObjectJSON), \(innerObjectJSON) ]
    }
    """.data(using: String.Encoding.utf8)

print("Nested Array of Objects:")

do {
    let result = try JSONDecoder().decode([String: [Animal]].self, from: jsonDataNestedArray!)
    result["en"]!.forEach ({ print($0.fileURLPath) }) // This one works
} catch { print(error) }

print("\n\n Single Object:")
do {
    let result = try JSONDecoder().decode(Animal.self, from: innerObjectData!)
        print(result.fileURLPath)
} catch { print(error) }

print("\n\nNested Object:")
do {
    let result = try JSONDecoder().decode([String: Animal].self, from:jsonDataNestedObject!)
        print(result["en"]!.fileURLPath) // I would also expect this to work but I get the error: "fatal error: Dictionary<String, Animal> does not conform to Decodable because Animal does not conform to Decodable.: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.45.6/src/swift/stdlib/public/core/Codable.swift, line 3420"
} catch { print(error) }

最佳答案

如果您不想等到下一个发行版,可以使用struct:

import Cocoa

struct Animal: Codable {
    var fileURLPath: String
    var age: Double
    var height: Double
    var weight: Double

    private enum CodingKeys: String, CodingKey {
        case fileURLPath = "path"
        case age, height, weight
    }
}

let innerObjectJSON = """
{
"path": "tiger_pic.png",
"age": 9,
"height": 1.23,
"weight": 130
}
"""

let innerObjectData = innerObjectJSON.data(using: String.Encoding.utf8)

let jsonDataNestedObject = """
    { "en" : \(innerObjectJSON)
    }
    """.data(using: String.Encoding.utf8)


print("\n\nNested Object:")
do {
    let result = try JSONDecoder().decode([String: Animal].self, from:jsonDataNestedObject!)
    print(result["en"]!.fileURLPath)
} catch { print(error) }

这给了我
Nested Object:
tiger_pic.png
["en": __lldb_expr_190.Animal(fileURLPath: "tiger_pic.png", age: 9.0, height: 1.23, weight: 130.0)]

它可以轻松解码,但是不使用TimeInterval,它只是Double的别名。

10-06 09:34