Skip to content

Commit 813b657

Browse files
authored
Allow Codable compliant values in json's init(any). (#302)
* Allow Codable compliant values in json's init(any). * updated test
1 parent 33f07bd commit 813b657

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

Sources/Segment/Utilities/JSON.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public enum JSON: Equatable {
7676
public init<T: Codable>(with value: T) throws {
7777
let encoder = JSONSafeEncoder.default
7878
let json = try encoder.encode(value)
79-
let output = try JSONSerialization.jsonObject(with: json)
79+
let output = try JSONSerialization.jsonObject(with: json, options: .fragmentsAllowed)
8080
try self.init(output)
8181
}
8282

@@ -113,6 +113,8 @@ public enum JSON: Equatable {
113113
self = .object(try object.mapValues(JSON.init))
114114
case let json as JSON:
115115
self = json
116+
case let codable as Codable:
117+
self = try Self.init(with: codable)
116118
// we don't work with whatever is being supplied
117119
default:
118120
throw JSONError.nonJSONType(type: "\(value.self)")

Tests/Segment-Tests/JSON_Tests.swift

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,4 +411,59 @@ class JSONTests: XCTestCase {
411411
XCTFail()
412412
}
413413
}
414+
415+
func testJSONCodableDict() throws {
416+
enum StringEnum: String, Codable {
417+
case test1
418+
case test2
419+
case test3
420+
}
421+
422+
enum IntEnum: Int, Codable {
423+
case test1
424+
case test2
425+
case test3
426+
}
427+
428+
struct SubStruct: Codable {
429+
var x: Int = 23
430+
}
431+
432+
struct CodableStruct: Codable {
433+
var a: Int = 47
434+
var b: String = "hello"
435+
var c: SubStruct = SubStruct()
436+
}
437+
438+
let dict: [String: Any] = [
439+
"uuid": UUID(),
440+
"strEnum": StringEnum.test2,
441+
"intEnum": IntEnum.test2,
442+
"struct": CodableStruct()
443+
]
444+
445+
do {
446+
let json = try JSON(dict)
447+
print(json.prettyPrint())
448+
449+
let strEnum: String? = json[keyPath: "strEnum"]
450+
XCTAssertEqual(strEnum, "test2")
451+
452+
let intEnum: Int? = json[keyPath: "intEnum"]
453+
XCTAssertEqual(intEnum, 1)
454+
455+
let b: String? = json[keyPath: "struct.b"]
456+
XCTAssertEqual(b, "hello")
457+
458+
let x: Int? = json[keyPath: "struct.c.x"]
459+
XCTAssertEqual(x, 23)
460+
461+
let uuid: String? = json[keyPath: "uuid"]
462+
XCTAssertEqual(uuid!.count, 36)
463+
464+
} catch {
465+
print(error)
466+
XCTFail()
467+
}
468+
}
414469
}

0 commit comments

Comments
 (0)