JSONSerializing.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright 2025, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import GRPCCore
  17. import struct Foundation.Data
  18. import class Foundation.JSONDecoder
  19. import class Foundation.JSONEncoder
  20. @available(gRPCSwift 2.0, *)
  21. struct JSONSerializer<Message: Codable>: MessageSerializer {
  22. func serialize<Bytes: GRPCContiguousBytes>(_ message: Message) throws -> Bytes {
  23. do {
  24. let jsonEncoder = JSONEncoder()
  25. let data = try jsonEncoder.encode(message)
  26. return Bytes(data)
  27. } catch {
  28. throw RPCError(code: .internalError, message: "Can't serialize message to JSON. \(error)")
  29. }
  30. }
  31. }
  32. @available(gRPCSwift 2.0, *)
  33. struct JSONDeserializer<Message: Codable>: MessageDeserializer {
  34. func deserialize<Bytes: GRPCContiguousBytes>(_ serializedMessageBytes: Bytes) throws -> Message {
  35. do {
  36. let jsonDecoder = JSONDecoder()
  37. let data = serializedMessageBytes.withUnsafeBytes { Data($0) }
  38. return try jsonDecoder.decode(Message.self, from: data)
  39. } catch {
  40. throw RPCError(code: .internalError, message: "Can't deserialze message from JSON. \(error)")
  41. }
  42. }
  43. }