Skip to content

Commit c7d1eb4

Browse files
committed
Fix Encodable error
1 parent 5d81bc3 commit c7d1eb4

File tree

2 files changed

+43
-6
lines changed

2 files changed

+43
-6
lines changed

Sources/Lookup/Lookup.swift

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,25 @@ public struct Lookup: @unchecked Sendable {
122122
self.rawType = .array
123123

124124
case _ as AnyObject:
125-
self.rawDict = mirrors(reflecting: jsonObject)
126-
self.rawType = .object
125+
switch jsonObject {
126+
case let encodable as Encodable:
127+
do {
128+
let data = try JSONEncoder().encode(encodable)
129+
if let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
130+
self.rawDict = dict
131+
self.rawType = .object
132+
} else {
133+
self.rawType = .none
134+
}
135+
} catch {
136+
self.rawType = .none
137+
}
138+
139+
default:
140+
self.rawDict = mirrors(reflecting: jsonObject)
141+
self.rawType = .object
142+
}
143+
127144
default:
128145
self.rawType = .none
129146
}
@@ -992,3 +1009,4 @@ extension Lookup {
9921009
}
9931010
}
9941011
}
1012+

Tests/LookupTests/LookupTests.swift

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@ import Foundation
55
import UIKit
66
#endif
77

8+
struct CodableObject: Codable, Identifiable {
9+
let id: UUID
10+
var text: String
11+
12+
enum CodingKeys: String, CodingKey {
13+
case id, text = "t_ext"
14+
}
15+
}
16+
817
struct Params {
918
let lookup: Lookup
1019
init(_ lookup: Lookup) {
@@ -498,11 +507,11 @@ struct LookupTests {
498507
#expect(lookup.toID.string == "10086")
499508
#expect(lookup.toID.int == 10086)
500509

501-
#expect(lookup.markup.keyboards.0.0.text.string == "Hang up")
502-
#expect(lookup.markup.keyboards.0.0.callbackData.string == "/hang-up")
510+
#expect(lookup.markup.inline_keyboard.0.0.text.string == "Hang up")
511+
#expect(lookup.markup.inline_keyboard.0.0.callback_data.string == "/hang-up")
503512

504-
#expect(lookup.markup.keyboards.1.0.text.string == "Recording")
505-
#expect(lookup.markup.keyboards.1.0.callbackData.string == "/recording")
513+
#expect(lookup.markup.inline_keyboard.1.0.text.string == "Recording")
514+
#expect(lookup.markup.inline_keyboard.1.0.callback_data.string == "/recording")
506515
}
507516

508517
@Test("Test Unwrap")
@@ -528,6 +537,16 @@ struct LookupTests {
528537
#expect(lookup.ids.count == 1)
529538
}
530539

540+
// Codable 需要获取 CodingKeys 的结果,否则服务端会出问题。。。
541+
@Test("Test Codable Object")
542+
func testCodableObject() throws {
543+
544+
let lookup = Lookup(CodableObject(id: UUID(), text: "Hello, world!"))
545+
print(lookup.description)
546+
// t_ext is Codable `CodingKey`
547+
#expect(lookup.t_ext.string == "Hello, world!")
548+
}
549+
531550
#if os(iOS)
532551
@Test("Test UIView")
533552
func testUIView() throws {

0 commit comments

Comments
 (0)