Skip to content

Commit

Permalink
feature(Saby): add support boolean from NSNumber
Browse files Browse the repository at this point in the history
  • Loading branch information
0xWOF committed Jun 17, 2024
1 parent c624f1f commit 164dd3d
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Source/JSON/Construct/JSONConvert.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,14 @@ extension JSON {

extension JSON {
public static func from(unsafe value: Any?) throws -> JSON {
if let value = value as? Double, !value.isNaN, !value.isInfinite {
if
let value = value as? NSNumber,
value === kCFBooleanTrue || value === kCFBooleanFalse,
let value = value as? Bool
{
return .boolean(value)
}
else if let value = value as? Double, !value.isNaN, !value.isInfinite {
return .number(value)
}
else if let value = value as? Float, !value.isNaN, !value.isInfinite {
Expand Down
47 changes: 47 additions & 0 deletions Test/JSON/Construct/JSONConvertTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,46 @@ final class JSONConvertTest: XCTestCase {
XCTAssertEqual(json, decoded)
}

func test__from_json_serialization() {
let json = JSON.from([
"a": "a",
"b": 1,
"c": [
"a": "a",
"b": 1,
"c": true
],
"d": [
"a",
1,
true
],
"e": nil
])
let string = """
{
"a": "a",
"b": 1,
"c": {
"a": "a",
"b": 1,
"c": true
},
"d": [
"a",
1,
true
],
"e": null
}
"""

XCTAssertEqual(
try! JSON.from(unsafe: JSONSerialization.jsonObject(with: string.data(using: .utf8)!)),
json
)
}

func test__from_encodable() {
let json = JSON.from([
"a": "123",
Expand Down Expand Up @@ -152,4 +192,11 @@ final class JSONConvertTest: XCTestCase {
XCTAssertEqual(JSON.from(unsafe: [nil,1,JSONEncoder()]), JSON.from([nil,1]))
XCTAssertEqual(JSON.from(unsafe: [[JSONEncoder(),nil],[1,2,3]]), JSON.from([[nil],[1,2,3]]))
}

func test__from_nsnumber() {
XCTAssertEqual(try! JSON.from(unsafe: NSNumber(integerLiteral: 1)), JSON.from(1))
XCTAssertEqual(try! JSON.from(unsafe: NSNumber(floatLiteral: 1.0)), JSON.from(1.0))
XCTAssertEqual(try! JSON.from(unsafe: NSNumber(booleanLiteral: true)), JSON.from(true))
XCTAssertEqual(try! JSON.from(unsafe: NSNumber(booleanLiteral: false)), JSON.from(false))
}
}

0 comments on commit 164dd3d

Please sign in to comment.