Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Fix 0 and 1 encoded as bool in JSON #76

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions Sources/AnyCodable/AnyEncodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ extension _AnyEncodable {
#endif
case is Void:
try container.encodeNil()
#if canImport(Foundation)
case let number as NSNumber:
try encode(nsnumber: number, into: &container)
#endif
case let bool as Bool:
try container.encode(bool)
case let int as Int:
Expand Down Expand Up @@ -87,8 +91,6 @@ extension _AnyEncodable {
case let string as String:
try container.encode(string)
#if canImport(Foundation)
case let number as NSNumber:
try encode(nsnumber: number, into: &container)
case let date as Date:
try container.encode(date)
case let url as URL:
Expand All @@ -108,6 +110,11 @@ extension _AnyEncodable {

#if canImport(Foundation)
private func encode(nsnumber: NSNumber, into container: inout SingleValueEncodingContainer) throws {
if CFGetTypeID(nsnumber) == CFBooleanGetTypeID() {
try container.encode(nsnumber.boolValue)
return
}

switch Character(Unicode.Scalar(UInt8(nsnumber.objCType.pointee))) {
case "B":
try container.encode(nsnumber.boolValue)
Expand Down
11 changes: 11 additions & 0 deletions Tests/AnyCodableTests/AnyEncodableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,17 @@ class AnyEncodableTests: XCTestCase {
XCTAssert(encodedJSONObject["double"] is Double)
}

func testEncodeNSNumberOneAndZeroAsInt() throws {
let dictionary: [NSNumber] = [0, 1]

let encoder = JSONEncoder()

let json = try encoder.encode(AnyEncodable(dictionary))
let jsonString = String(data: json, encoding: .utf8)!

XCTAssertEqual(jsonString, "[0,1]")
}

func testStringInterpolationEncoding() throws {
let dictionary: [String: AnyEncodable] = [
"boolean": "\(true)",
Expand Down