Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/krzyzanowskim/jsoncodable
JSON Codable is what we need 90% of the time
https://github.com/krzyzanowskim/jsoncodable
json swift
Last synced: 2 months ago
JSON representation
JSON Codable is what we need 90% of the time
- Host: GitHub
- URL: https://github.com/krzyzanowskim/jsoncodable
- Owner: krzyzanowskim
- License: mit
- Created: 2020-01-05T22:13:09.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2020-01-09T11:48:25.000Z (almost 5 years ago)
- Last Synced: 2024-04-14T07:11:17.856Z (9 months ago)
- Topics: json, swift
- Language: Swift
- Homepage: https://twitter.com/krzyzanowskim/status/1213943161309011969
- Size: 28.3 KB
- Stars: 75
- Watchers: 5
- Forks: 6
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# JSONCodable
JSON Codable is what we need 90% of the time.
## Usage
```swift
struct Filter: JSONCodable {
let id: String
}let jsonString = try Filter(id: "foo").toJSON()
```or use `CodableFormat`:
```swift
struct Filter: Codable {
let id: String
}let data = try Filter(id: "foo").to(.json)
let filter = try Filter.from(data, format: .json)
```### Custom format
To add custom format, add it to `CodableFormat` like this:
```swift
extension CodableFormat {private static var jsonSnakeCaseEncoder: JSONEncoder {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}private static var jsonSnakeCaseDecoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}// Custom format
static let jsonSnakeCase = CodableFormat("jsonSnakeCase", jsonSnakeCaseEncoder, jsonSnakeCaseDecoder)
}// use jsonSnakeCase format
let json = try Filter(id: "foo").to(.jsonSnakeCase)
```## Installation
Copy `JSONCodable.swift` to your project, or
### Swift Package Manager
To depend on the package, you need to declare your dependency in your `Package.swift`:
```swift
.package(url: "https://github.com/krzyzanowskim/JSONCodable.git", from: "1.2.0"),
```and to your application/library target, add "JSONCodable" to your dependencies, e.g. like this:
```swift
.target(name: "BestExampleApp", dependencies: ["JSONCodable"]),
```