【问题标题】:Swift 5 - JSONEncoder with nested JSONSwift 5 - 带有嵌套 JSON 的 JSONEncoder
【发布时间】:2021-12-11 10:45:52
【问题描述】:

我正在尝试使用 JSONEncoder()[[String : String]] 编码为 JSON 嵌套对象。

Swift 输出示例:

[["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]

JSON 编码后的预期输出:

[
  {
    "firstName": "John",
    "lastName": "Doe"
  },

  {
    "firstName": "Tim",
    "lastName": "Cook"
  }
]

我将如何遍历这个字典数组,然后用JSONEncoder().encode() 对其进行编码?非常感谢!

【问题讨论】:

    标签: ios json swift iphone


    【解决方案1】:

    JSONEncoder 默认为您提供Data。要将其恢复为 String 表单,您可以使用:

    let input = [["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
    
    do {
        let json = try JSONEncoder().encode(input)
        print(String(decoding: json, as: UTF8.self))
    } catch {
        print(error)
    }
    

    产量:

    [{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]

    【讨论】:

      【解决方案2】:

      使用Codable 编码/解码 JSON 数据。首先,将 JSON 转换为这样的对象,如果您更新更多字段会更容易:

      struct Person: Codable {
          var firstName: String
          var lastName: String
      }
      

      假设你有一个Person 数组

      var persons = [Person]()
      persons.append(.init(firstName: "John", lastName: "Doe"))
      persons.append(.init(firstName: "Tim", lastName: "Cook"))
      
      //PRINT OUT
      let jsonData = try! JSONEncoder().encode(persons)
      let jsonString = String(data: jsonData, encoding: .utf8)
      

      这是输出:

      "[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 2021-07-18
        • 1970-01-01
        • 2019-05-07
        • 1970-01-01
        相关资源
        最近更新 更多