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

JSONSingleValueEncodingContainer.encode<T> isn't implemented #20

Closed adam-fowler closed 4 years ago

adam-fowler commented 4 years ago

The following code returns null when it should return {"firstName":"Adam","surname":"Fowler"}. This is caused by JSONSingleValueEncodingContainer.encode not encoding anything.

struct Name: Encodable {
    var firstName: String
    var surname: String
}

struct Object: Encodable {
    var name: Name

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(name)
    }
}

let object = Object(name: Name(firstName: "Adam", surname: "Fowler"))
let json = try JSONEncoder().encode(object)

In the following situation it causes the encoder to crash in JSONKeyedEncodingContainer.encode as it is expecting a value back but nothing is returned.

@propertyWrapper
struct Coding<Value: Encodable>: Encodable {
    var wrappedValue: Value

    init(wrappedValue: Value) {
        self.wrappedValue = wrappedValue
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(wrappedValue)
    }
}

struct Object: Encodable {
    @Coding var name: String
}

let object = Object(name: "Adam Fowler")
let json = try PureSwiftJSONCoding.JSONEncoder().encode(object)