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

[SR-7213] Allow JSONEncoder to Encode Top-Level Fragments #4038

Closed
swift-ci opened this issue Mar 16, 2018 · 1 comment
Closed

[SR-7213] Allow JSONEncoder to Encode Top-Level Fragments #4038

swift-ci opened this issue Mar 16, 2018 · 1 comment

Comments

@swift-ci
Copy link
Contributor

Previous ID SR-7213
Radar None
Original Reporter fabb (JIRA User)
Type Improvement
Status Resolved
Resolution Duplicate
Additional Detail from JIRA
Votes 1
Component/s Foundation, Standard Library
Labels Improvement, Codable
Assignee None
Priority Medium

md5: 4ba04756c592207606907d54614a872f

duplicates:

  • SR-6163 JSONDecoder cannot decode RFC 7159 JSON

Issue Description:

Codable single values that are not containers currently cannot be converted to json with JSONEncoder.

That would be helpful though, example use case: Persist a simple enum to UserDefaults.

Example code:

enum E: Int, Codable {
    case one
}

func saveCodableToUserDefaults<T: Codable>(_ object: T, forKey key: String) {
    do {
        // note that we could use either PropertyListEncoder or JSONEncoder, we decided for JSONEncoder - do never change, or old data will not be able to be read again
        let data = try JSONEncoder().encode(object)
        UserDefaults.standard.set(data, forKey: key)
    }
    catch {
        assertionFailure()
    }
}

saveCodableToUserDefaults(E.one, forKey: "test") // assertionFailure

Also see discussion:
https://forums.swift.org/t/top-level-t-self-encoded-as-number-json-fragment/11001

@itaiferber
Copy link
Contributor

Apologies, looks like this was already filed as SR-6163. 🙁 Let's track it there.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
@shahmishal shahmishal transferred this issue from apple/swift May 5, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants