Skip to content

Commit

Permalink
Init numbers as Decimal before encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewheard committed Feb 28, 2024
1 parent 04021e4 commit 6ab6377
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Sources/GoogleAI/JSONValue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ extension JSONValue: Encodable {
case .null:
try container.encodeNil()
case let .number(numberValue):
try container.encode(numberValue)
try container.encode(Decimal(numberValue))
case let .string(stringValue):
try container.encode(stringValue)
case let .bool(boolValue):
Expand Down
8 changes: 6 additions & 2 deletions Tests/GoogleAITests/JSONValueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ final class JSONValueTests: XCTestCase {

let numberKey = "pi"
let numberValue = 3.14159
let numberValueEncoded = "3.14159"
let stringKey = "hello"
let stringValue = "Hello, world!"

Expand Down Expand Up @@ -127,7 +128,10 @@ final class JSONValueTests: XCTestCase {
let jsonData = try encoder.encode(JSONValue.object(objectValue))

let json = try XCTUnwrap(String(data: jsonData, encoding: .utf8))
XCTAssertEqual(json, "{\"\(stringKey)\":\"\(stringValue)\",\"\(numberKey)\":\(numberValue)}")
XCTAssertEqual(
json,
"{\"\(stringKey)\":\"\(stringValue)\",\"\(numberKey)\":\(numberValueEncoded)}"
)
}

func testEncodeArray() throws {
Expand All @@ -136,6 +140,6 @@ final class JSONValueTests: XCTestCase {
let jsonData = try encoder.encode(JSONValue.array(arrayValue))

let json = try XCTUnwrap(String(data: jsonData, encoding: .utf8))
XCTAssertEqual(json, "[null,\(numberValue)]")
XCTAssertEqual(json, "[null,\(numberValueEncoded)]")
}
}

0 comments on commit 6ab6377

Please sign in to comment.