Serializer.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  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. //
  17. // JSONSerializer.swift
  18. // HandyJSON
  19. //
  20. // Created by zhouzhuo on 9/30/16.
  21. //
  22. import Foundation
  23. public extension HandyJSON {
  24. func toJSON() -> [String: Any]? {
  25. if let dict = Self._serializeAny(object: self) as? [String: Any] {
  26. return dict
  27. }
  28. return nil
  29. }
  30. func toJSONString(prettyPrint: Bool = false) -> String? {
  31. if let anyObject = self.toJSON() {
  32. if JSONSerialization.isValidJSONObject(anyObject) {
  33. do {
  34. let jsonData: Data
  35. if prettyPrint {
  36. jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: [.prettyPrinted])
  37. } else {
  38. jsonData = try JSONSerialization.data(withJSONObject: anyObject, options: [])
  39. }
  40. return String(data: jsonData, encoding: .utf8)
  41. } catch let error {
  42. InternalLogger.logError(error)
  43. }
  44. } else {
  45. InternalLogger.logDebug("\(anyObject)) is not a valid JSON Object")
  46. }
  47. }
  48. return nil
  49. }
  50. }
  51. public extension Collection where Iterator.Element: HandyJSON {
  52. func toJSON() -> [[String: Any]?] {
  53. return self.map{ $0.toJSON() }
  54. }
  55. func toJSONString(prettyPrint: Bool = false) -> String? {
  56. let anyArray = self.toJSON()
  57. if JSONSerialization.isValidJSONObject(anyArray) {
  58. do {
  59. let jsonData: Data
  60. if prettyPrint {
  61. jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: [.prettyPrinted])
  62. } else {
  63. jsonData = try JSONSerialization.data(withJSONObject: anyArray, options: [])
  64. }
  65. return String(data: jsonData, encoding: .utf8)
  66. } catch let error {
  67. InternalLogger.logError(error)
  68. }
  69. } else {
  70. InternalLogger.logDebug("\(self.toJSON()) is not a valid JSON Object")
  71. }
  72. return nil
  73. }
  74. }