Skip to content

Commit

Permalink
codingSrategy fix and sample
Browse files Browse the repository at this point in the history
  • Loading branch information
evermeer committed Sep 20, 2018
1 parent ca58c87 commit bfcb6c8
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 10 deletions.
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,6 @@ perl -p -e "s/($KEYWORDS)/ warning: \$1/"

You can install this by adding the following line to your Podfile:

⚠️WARNING: Swift 4 or later is required ⚠️

```
pod "Stuff/Codable"
```
Expand All @@ -216,7 +214,7 @@ And here you can see how you can use these Stuff/Codable functions:

```swift
func test() {
let initialObject = TestCodable(naam: "Edwin", id: 1)
let initialObject = TestCodable(naam: "Edwin", id: 1, testField: "tst")

guard let json = initialObject.toJsonString() else {
print("Could not create json from object")
Expand Down Expand Up @@ -245,11 +243,18 @@ func test() {
return
}
print("inner object from json \(String(describing: innerObject))")

guard let custom = try TestCodable(json: "{\"Naam\":\"UpperN\", \"Id\":5, \"Test_field\":\"lowerSnake\"}", keyPath: nil, codingStrategy: customCodingStragegy) else {
print("Could not custom case convert")
return
}
print("read object with custom key coding from json to \(String(describing:
}
struct TestCodable : Codable {
var naam: String?
var id: Int?
var testField: String?
}
```
Expand Down
30 changes: 26 additions & 4 deletions Source/Codable/Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ enum CodingError : Error {
case RuntimeError(String)
}

struct AnyKey: CodingKey {
var stringValue: String
var intValue: Int?

init(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}

init(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}

public var customCodingStragegy: JSONDecoder.KeyDecodingStrategy = .custom { keys in
let lastComponent = keys.last!.stringValue
let snakeCased = lastComponent.split(separator: "_").map { $0.prefix(1).uppercased() + $0.dropFirst() }.reduce("") { $0 + $1}
let lowerFirst = snakeCased.prefix(1).lowercased() + snakeCased.dropFirst()
return AnyKey(stringValue: lowerFirst)
}

public extension Encodable {
/**
Convert this object to json data
Expand Down Expand Up @@ -94,9 +116,9 @@ public extension Decodable {
- parameter json: The json string
- parameter keyPath: for if you want something else than the root object
*/
init(json: String, keyPath: String? = nil) throws {
init(json: String, keyPath: String? = nil, codingStrategy: JSONDecoder.KeyDecodingStrategy = .convertFromSnakeCase) throws {
guard let data = json.data(using: .utf8) else { throw CodingError.RuntimeError("cannot create data from string") }
try self.init(data: data, keyPath: keyPath)
try self.init(data: data, keyPath: keyPath, codingStrategy: codingStrategy)
}

/**
Expand All @@ -105,9 +127,9 @@ public extension Decodable {
- parameter data: The json data
- parameter keyPath: for if you want something else than the root object
*/
init(data: Data, keyPath: String? = nil, codingStragegy: JSONDecoder.KeyDecodingStrategy = .convertFromSnakeCase) throws {
init(data: Data, keyPath: String? = nil, codingStrategy: JSONDecoder.KeyDecodingStrategy = .convertFromSnakeCase) throws {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.keyDecodingStrategy = codingStrategy
if let keyPath = keyPath {
let topLevel = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
guard let nestedJson = (topLevel as AnyObject).value(forKeyPath: keyPath) else { throw CodingError.RuntimeError("Cannot decode data to object") }
Expand Down
2 changes: 1 addition & 1 deletion Stuff.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "Stuff"
s.version = "0.6.1"
s.version = "0.7.0"
s.summary = "Too small for a library, too important to just forget"

s.description = <<-EOS
Expand Down
14 changes: 12 additions & 2 deletions StuffTests/CodableStuffTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import XCTest
class CodingStuffTests: XCTestCase {

func test() {
let initialObject = TestCodable(naam: "Edwin", id: 1)
let initialObject = TestCodable(naam: "Edwin", id: 1, testField: "tst")

guard let json = initialObject.toJsonString() else {
print("Could not create json from object")
Expand Down Expand Up @@ -46,7 +46,16 @@ class CodingStuffTests: XCTestCase {
return
}
print("inner object from json \(String(describing: innerObject))")


do {
let custom = try TestCodable(json: "{\"Naam\":\"UN\", \"Id\":5, \"Test_field\":\"tst\"}", keyPath: nil, codingStrategy: customCodingStragegy)
print("read object with custom key coding from json to \(String(describing: custom))")
} catch {
print("Could not custom case convert \(error)")
assertionFailure()
return
}

do {
try initialObject.saveToDocuments("myFile.dat")
} catch {
Expand Down Expand Up @@ -80,4 +89,5 @@ class CodingStuffTests: XCTestCase {
struct TestCodable : Codable {
var naam: String?
var id: Int?
var testField: String?
}

0 comments on commit bfcb6c8

Please sign in to comment.