Message+JSONAdditions_Data.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Sources/SwiftProtobuf/Message+JSONAdditions_Data.swift - JSON format primitive types
  2. //
  3. // Copyright (c) 2022 Apple Inc. and the project authors
  4. // Licensed under Apache License v2.0 with Runtime Library Exception
  5. //
  6. // See LICENSE.txt for license information:
  7. // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
  8. //
  9. // -----------------------------------------------------------------------------
  10. ///
  11. /// Extensions to `Message` to support JSON encoding/decoding using ``Foundation/Data``.
  12. ///
  13. // -----------------------------------------------------------------------------
  14. import Foundation
  15. /// JSON encoding and decoding methods for messages.
  16. extension Message {
  17. /// Creates a new message by decoding the given `Data` containing a serialized message
  18. /// in JSON format, interpreting the data as UTF-8 encoded text.
  19. ///
  20. /// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
  21. /// as UTF-8 encoded text.
  22. /// - Parameter options: The JSONDecodingOptions to use.
  23. /// - Throws: ``SwiftProtobufError`` or ``JSONDecodingError`` if decoding fails.
  24. public init(
  25. jsonUTF8Data: Data,
  26. options: JSONDecodingOptions = JSONDecodingOptions()
  27. ) throws {
  28. try self.init(jsonUTF8Bytes: jsonUTF8Data, extensions: nil, options: options)
  29. }
  30. /// Creates a new message by decoding the given `Data` containing a serialized message
  31. /// in JSON format, interpreting the data as UTF-8 encoded text.
  32. ///
  33. /// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
  34. /// as UTF-8 encoded text.
  35. /// - Parameter extensions: The extension map to use with this decode
  36. /// - Parameter options: The JSONDecodingOptions to use.
  37. /// - Throws: ``SwiftProtobufError`` or ``JSONDecodingError`` if decoding fails.
  38. public init(
  39. jsonUTF8Data: Data,
  40. extensions: (any ExtensionMap)? = nil,
  41. options: JSONDecodingOptions = JSONDecodingOptions()
  42. ) throws {
  43. try self.init(jsonUTF8Bytes: jsonUTF8Data, extensions: extensions, options: options)
  44. }
  45. /// Returns a Data containing the UTF-8 JSON serialization of the message.
  46. ///
  47. /// Unlike binary encoding, presence of required fields is not enforced when
  48. /// serializing to JSON.
  49. ///
  50. /// - Returns: A Data containing the JSON serialization of the message.
  51. /// - Parameters:
  52. /// - options: The JSONEncodingOptions to use.
  53. /// - Throws: ``SwiftProtobufError`` or ``JSONEncodingError`` if encoding fails.
  54. public func jsonUTF8Data(
  55. options: JSONEncodingOptions = JSONEncodingOptions()
  56. ) throws -> Data {
  57. try jsonUTF8Bytes(options: options)
  58. }
  59. }