diff --git a/Sources/Purchasing/Offering.swift b/Sources/Purchasing/Offering.swift index 31991f3521..e7ebb84ef6 100644 --- a/Sources/Purchasing/Offering.swift +++ b/Sources/Purchasing/Offering.swift @@ -310,20 +310,21 @@ extension Offering { } /// - Returns: The `metadata` value associated to `key` for the expected `Decodable` type, - /// or `nil` if not found. - /// - Throws: Error if the content couldn't be deserialized to the expected type. + /// or `nil` if not found or if the content couldn't be deserialized to the expected type. /// - Note: This decodes JSON using `JSONDecoder.KeyDecodingStrategy.convertFromSnakeCase`. public func getMetadataValue(for key: String) -> T? { - do { - guard let value = self.metadata[key] else { return nil } - let data = try JSONSerialization.data(withJSONObject: value) - - return try JSONDecoder.default.decode( - T.self, - jsonData: data, - logErrors: true - ) - } catch { + guard let value = self.metadata[key] else { return nil } + + if JSONSerialization.isValidJSONObject(value), + let data = try? JSONSerialization.data(withJSONObject: value) { + return try? JSONDecoder.default.decode( + T.self, + jsonData: data, + logErrors: true + ) + } else if let value = value as? T { + return value + } else { return nil } } diff --git a/Tests/UnitTests/Purchasing/OfferingsTests.swift b/Tests/UnitTests/Purchasing/OfferingsTests.swift index 2b011e74a0..50f093b72a 100644 --- a/Tests/UnitTests/Purchasing/OfferingsTests.swift +++ b/Tests/UnitTests/Purchasing/OfferingsTests.swift @@ -410,6 +410,18 @@ class OfferingsTests: TestCase { let wrongMetadataType = offeringA.getMetadataValue(for: "string", default: 5.5) expect(wrongMetadataType) == 5.5 + let intWithoutDefault: Int? = offeringA.getMetadataValue(for: "int") + expect(intWithoutDefault) == 5 + + let doubleWithoutDefault: Double? = offeringA.getMetadataValue(for: "double") + expect(doubleWithoutDefault) == 5.5 + + let boolWithoutDefault: Bool? = offeringA.getMetadataValue(for: "boolean") + expect(boolWithoutDefault) == true + + let stringWithoutDefault: String? = offeringA.getMetadataValue(for: "string") + expect(stringWithoutDefault) == "five" + struct Data: Decodable, Equatable { var number: Int }