swift-extras / swift-extras-json

JSON encoding and decoding without the use of Foundation in pure Swift.
Apache License 2.0
348 stars 15 forks source link

JSONEncoder.codingPath stack is not updated #21

Closed adam-fowler closed 4 years ago

adam-fowler commented 4 years ago

The coding path stack is not updated as you create/delete containers.

adam-fowler commented 4 years ago

The following outputs {"sub":{}} when it should output {"sub":{"key":"sub","value":12}}. The encoders are expected to keep the codingPath up to date but the use cases are fairly obscure so this isn't a huge issue.

struct SubObject: Encodable {
    let value: Int

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let key = encoder.codingPath.last {
            try container.encode(key.stringValue, forKey: .key)
            try container.encode(value, forKey: .value)
        }
    }

    private enum CodingKeys: String, CodingKey {
    case key = "key"
    case value = "value"
    }
}

struct Object: Encodable {
    let sub: SubObject
}

let o = Object(sub: SubObject(value: 12))
let json = try PureSwiftJSONCoding.JSONEncoder().encode(o)
print(String(decoding: json, as: Unicode.UTF8.self))