Skip to content
JSON Codable is what we need 90% of the time
Swift
Branch: master
Clone or download
Latest commit d31a47d Jan 9, 2020
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github/workflows
Sources/JSONCodable Decode string Jan 8, 2020
Tests
.gitignore Code Jan 5, 2020
LICENSE Initial commit Jan 5, 2020
Package.swift
README.md Fix example Jan 7, 2020

README.md

JSONCodable

JSON Codable is what we need 90% of the time.

Usage

struct Filter: JSONCodable {
  let id: String
}

let jsonString = try Filter(id: "foo").toJSON()

or use CodableFormat:

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:

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:

.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:

.target(name: "BestExampleApp", dependencies: ["JSONCodable"]),
You can’t perform that action at this time.