在 Swift 中将字典转换为 JSON

swiftserver side programmingprogramming更新于 2025/10/11 0:53:00

Swift 提供了一个名为 JSONSerialization 的类,用于将字典转换为 JSON 字符串。我们将使用这两个步骤在 Swift 语言中将字典转换为 JSON 字符串。步骤如下 -

  • 使用 JSONSerialization.data() 方法将字典转换为 JSON 数据格式,该方法将字典对象作为参数以及选项。

  • 现在使用 String(data:encoding:) 构造函数将 JSON 数据转换为 JSON 字符串格式。

在本文中,您将看到一些如何将字典转换为 JSON 字符串的示例。

JSONSerialization

iOS 和 macOS 的 Foundation 框架默认包含 JSONSerialization 类。要创建 Swift 字典或数组,此类需要一个字符串或数据对象。使用同一个类,您还可以将字典或数组转换为 JSON 对象。序列化和反序列化过程由 JSONSerialization 类处理。

以下是将字典转换为 JSON 字符串的示例

  • 步骤 1 - 创建一个全局函数,该函数将字典作为要转换的参数。

  • 步骤 2 - 使用 data(withJSONObject:options:) 方法将字典转换为 JSON 数据格式。

  • 步骤 3 - 处理此方法中的失败情况,因为 data() 方法返回可选数据值。

  • 步骤 4 - 使用 String(data:encoding) 方法将 JSON 数据转换为 JSON 字符串。

  • 步骤 5 − 处理失败情况,因为此方法返回一个可选的字符串值。

import Foundation
func convertDictionaryToJSON(_ dictionary: [String: Any]) -> String? {

   guard let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) else {
      print("Something is wrong while converting dictionary to JSON data.")
      return nil
   }

   guard let jsonString = String(data: jsonData, encoding: .utf8) else {
      print("Something is wrong while converting JSON data to JSON string.")
      return nil
   }

   return jsonString
}
let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
if let output = convertDictionaryToJSON(dictionary) {
   print("Input dictionary: \(dictionary)")
   print("Output JSON: \(output)")
}

输出

Input dictionary: ["age": 32, "name": "John Allen", "company": "Google Inc."]
Output JSON: {
   "age" : 32,
   "name" : "John Allen",
   "company" : "Google Inc."
}

请注意,如果字典包含无法转换为 JSON 的值(例如自定义对象或循环引用),则 data(withJSONObject:options:) 方法将抛出错误,并且不会执行 do-try-catch 块内的代码

使用扩展

还有另一种强烈推荐的方法将字典转换为 JSON 字符串。您可以创建一个扩展并将这些函数添加到该扩展。这将有助于在您的代码库中全局访问这些属性和方法。以下是如何使用扩展的示例。

扩展

import Foundation
extension Dictionary {
       
   var jsonData: Data? {
      return try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
   }
       
   func toJSONString() -> String? {
      if let jsonData = jsonData {
         let jsonString = String(data: jsonData, encoding: .utf8)
         return jsonString
      }
      return nil
   }
}

用法

func convertDictionaryToJSON() {
       
   let dictionary: [String: Any] = ["name": "John Allen", "age": 32, "company": "Google Inc."]
   guard let jsonData = dictionary.jsonData else {
      print("Something is wrong while converting dictionary to JSON data.")
      return
   }
   guard let jsonString = dictionary.toJSONString() else {
      print("Something is wrong while converting JSON data to JSON string.")
      return
   }
   print("Input dictionary: \(dictionary)")
   print("Output JSON: \(jsonString)")
}
convertDictionaryToJSON()

输出

Input dictionary: ["age": 32, "company": "Google Inc.", "name": "John Allen"]
Output JSON: {"age" : 32, "company" : "Google Inc.", "name" : "John Allen"}

结论

在 Swift 中,您可以通过低级 API 将原始 JSON 数据转换为数组或字典等集合。您可以使用 JSONSerialization 类将原始 JSON 对象转换为有意义的对象。此类内置于 Foundation 框架中。您可以在任何平台上使用此类,例如 iOS、macOS、watchOS 等。此外,以相反的顺序,您可以使用反序列化过程将自定义对象转换回原始 JSON 数据。

在 Swift 4 中,Apple 引入了 Codable 协议,使序列化和反序列化过程变得简单。此协议提供了一种灵活的方式来使用 JSON 数据来解析数据并将其存储到模型类/结构中。此协议可用于轻松地将模型对象转换为 JSON 数据。

Codable 协议有助于减少代码并处理序列化和反序列化过程,使代码更简洁、更易于维护。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部