Decodable icon indicating copy to clipboard operation
Decodable copied to clipboard

Decodable objects should be encodable back to JSON

Open kylebshr opened this issue 10 years ago • 3 comments

It would be really great for updating objects on your REST api if you could automatically encode Decodable objects back into JSON. I may look into implementing this, but wanted to hear thoughts on this, or if you're perhaps already working on it.

kylebshr avatar Oct 03 '15 03:10 kylebshr

Haven't thought about doing it automatically. I'm afraid it would be difficult to do unless changing the fundamental decoding approach to something more like Hearst-DD/ObjectMapper. If not doing it automatically one might just implement a simple Encodable protocol and be done:

public protocol Encodable {
    func encode() -> AnyObject 
}
extension Test: Encodable {
    func encode() -> AnyObject {
        return ["name": name, "owner": owner.encode()] // Not sure what return type should be used
    }
}

But that's really simple, and you could probably do that yourself instead of putting it in the framework.*

Or one could make some sugary-syntax for calling -encode on every object, and making standard types extensions for Encodable. But that would add a lot of complexity and subtract simplicity for the sake of sometimes not having to call -endode.

Those are my, not so optimistic thoughts. But if you come up with something :+1:

*) But encode should perhaps be throwing? In that case there is a lot of work to be done for making the errors awesome.

Anviking avatar Oct 03 '15 12:10 Anviking

Just saw that Genome does it in a nice way. (but can't map to uninitialized variables because of Swift)

Anviking avatar Nov 07 '15 18:11 Anviking

I like the fact that this is a single purpose lib. Decodable should just decode!

voidref avatar Feb 25 '16 20:02 voidref