Skip to content

Commit

Permalink
Add JSON data function (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xLeif authored Jun 10, 2023
1 parent 6ddb9ec commit a1ad092
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Sources/Cache/JSON/JSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ public struct JSON<Key: RawRepresentable & Hashable>: Cacheable where Key.RawVal
}
}

/// Returns JSON data.
///
/// - Throws: Errors are from `JSONSerialization.data(withJSONObject:)`
public func data() throws -> Data {
var stringKeyedValues: [String: Any] = [:]

for (key, value) in allValues {
stringKeyedValues[key.rawValue] = value
}

return try JSONSerialization.data(
withJSONObject: stringKeyedValues
)
}

/**
Retrieves a nested JSON object within the current object.

Expand Down
7 changes: 7 additions & 0 deletions Tests/CacheTests/JSONTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ final class JSONTests: XCTestCase {
XCTAssertEqual(json.get(.text), "Hello, World!")
XCTAssertEqual(json.get(.count), 27)
XCTAssertEqual(json.get(.isError), false)

let data = try json.data()
let loadedJSON: JSON<Key> = JSON(data: data)

XCTAssertEqual(loadedJSON.get(.text, as: String.self), json.get(.text))
XCTAssertEqual(loadedJSON.get(.count, as: Int.self), json.get(.count))
XCTAssertEqual(loadedJSON.get(.isError, as: Bool.self), json.get(.isError))
}

func testInitArray() throws {
Expand Down

0 comments on commit a1ad092

Please sign in to comment.