Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide Decoder to turn JSON into Decodable #34

Open
aomader opened this issue Dec 9, 2019 · 2 comments
Open

Provide Decoder to turn JSON into Decodable #34

aomader opened this issue Dec 9, 2019 · 2 comments

Comments

@aomader
Copy link

aomader commented Dec 9, 2019

Hej, it is nice to have JSON as an intermediate correctly-typed abstraction over same JSON data, but at some point I might still want to work with some dedicated data class. However, at that point I might only have the JSON left and I can not make use of some Decoder to turn my JSON into an appropriate Decodable for the task at hand.

I have a concret use case for that, where the concrete structure of my JSON is only clear at a later point in time.

Thus, I would suggest to provide a GenericJSONDecoder to turn a JSON into a Decodable. Analogous to JSONDecoder and Data.

The solution proposed here solves the issue in the meantime, but is really wasteful and rather just a short-time fix:

func decode<T: Decodable>(from json: JSON) throws -> T {
    let data = try JSONEncoder().encode(json)
    return try JSONDecoder().decode(T.self, from: data)
}
@zoul
Copy link
Collaborator

zoul commented Dec 10, 2019

Do you dislike the workaround via JSON data in principle (since it is a hack), or does it have particular technical problems for you?

@aomader
Copy link
Author

aomader commented Dec 10, 2019

It is not a technical problem, but rather a concern that this is not ideal and can get wasteful for larger JSON structures, as we have to convert back to a JSON string and than into a proper Decodable.

As we have done the JSON parsing already, it makes sense to not redo this work. Also it seems that I am not the only one missing that feature. It is basically a feature request. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants