Skip to content

Commit

Permalink
decoding strings and arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
Joannis committed Oct 23, 2017
1 parent bda835f commit 801f4fa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
16 changes: 14 additions & 2 deletions Sources/Cheetah/Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -374,9 +374,21 @@ public class JSONDecoder {
return try T(from: decoder)
}

public func decode<T : Decodable>(_ type: T.Type, from array: JSONArray) throws -> T {
let decoder = _JSONDecoder(target: .array(array))
return try T(from: decoder)
}

public func decode<T : Decodable>(_ type: T.Type, from string: String) throws -> T {
let object = try JSONObject(from: string)
let decoder = _JSONDecoder(target: .object(object))
let decoder: _JSONDecoder

if let object = try? JSONObject(from: string) {
decoder = _JSONDecoder(target: .object(object))
} else {
let array = try JSONArray(from: string)
decoder = _JSONDecoder(target: .array(array))
}

return try T(from: decoder)
}
}
Expand Down
5 changes: 5 additions & 0 deletions Tests/CheetahTests/ParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ class ParsingTests: XCTestCase {
XCTAssertEqual(Bool(obj1["other"]), false)
XCTAssertEqual(Bool(obj2["other"]), false)
XCTAssertEqual(Bool(obj3["other"]), true)

let encoded = array0.serializedString()
let values = try JSONDecoder().decode([User].self, from: encoded)

XCTAssertEqual(values.count, 4)
}

func testEncodeArrayJSON() throws {
Expand Down

0 comments on commit 801f4fa

Please sign in to comment.