File tree Expand file tree Collapse file tree 2 files changed +22
-0
lines changed
Expand file tree Collapse file tree 2 files changed +22
-0
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 {
You can’t perform that action at this time.
0 commit comments