Skip to content

Commit a1ad092

Browse files
authored
Add JSON data function (#2)
1 parent 6ddb9ec commit a1ad092

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

Sources/Cache/JSON/JSON.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,21 @@ public struct JSON<Key: RawRepresentable & Hashable>: Cacheable where Key.RawVal
7171
}
7272
}
7373

74+
/// Returns JSON data.
75+
///
76+
/// - Throws: Errors are from `JSONSerialization.data(withJSONObject:)`
77+
public func data() throws -> Data {
78+
var stringKeyedValues: [String: Any] = [:]
79+
80+
for (key, value) in allValues {
81+
stringKeyedValues[key.rawValue] = value
82+
}
83+
84+
return try JSONSerialization.data(
85+
withJSONObject: stringKeyedValues
86+
)
87+
}
88+
7489
/**
7590
Retrieves a nested JSON object within the current object.
7691

Tests/CacheTests/JSONTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ final class JSONTests: XCTestCase {
2424
XCTAssertEqual(json.get(.text), "Hello, World!")
2525
XCTAssertEqual(json.get(.count), 27)
2626
XCTAssertEqual(json.get(.isError), false)
27+
28+
let data = try json.data()
29+
let loadedJSON: JSON<Key> = JSON(data: data)
30+
31+
XCTAssertEqual(loadedJSON.get(.text, as: String.self), json.get(.text))
32+
XCTAssertEqual(loadedJSON.get(.count, as: Int.self), json.get(.count))
33+
XCTAssertEqual(loadedJSON.get(.isError, as: Bool.self), json.get(.isError))
2734
}
2835

2936
func testInitArray() throws {

0 commit comments

Comments
 (0)