json - 如何使用 Decodable 协议(protocol)将此 JSON 转换为 Swift 结构?

标签 json swift codable

注意:我已经看过这个问题 -> How do I use custom keys with Swift 4's Decodable protocol?但它没有解释如何编码/解码枚举

这是我想要的结构:

struct MyStruct: Decodable {
    let count: PostType
}

enum PostType: Decodable {
    case fast(value: Int, value2: Int)
    case slow(string: String, string2: String)
}

现在我知道我希望我的结构是什么样子,问题是:

  1. 我不知道 init 函数在 PostType 枚举中应该是什么样子。

我使用下面的代码来帮助我快速构建 JSON。

    let jsonData = """
    {
       "count": {
          "fast" :
           {
               "value": 4,
               "value2": 5
           }
       }
    }
    """.data(using: .utf8)!

    // Decoding
    do {
        let decoder = JSONDecoder()
        let response = try decoder.decode(MyStruct.self, from: jsonData)
        print(response)
    } catch {
        print(error)
    }

谁能帮我解决这个问题吗?

编辑1我的 JSON 看起来像这样

   {
        "count": {
           "fast" :
            {
                "value": 4,
                "value2": 5
            }
        }
    }

initPostType 枚举 中应该是什么样子?

最佳答案

由于具有关联类型的 enum 与任何 JSON 类型都不匹配,因此您需要更多的手工工作并编写自定义映射。

以下代码涵盖三个选项。

  • 以大小写为键的字典和以参数标签为键的包含字典
  • 将每个关联值编码/解码为单独的键/值对
  • 使用任意键对数组中的所有关联值进行编码/解码。

首先,枚举必须不符合Codable

enum PostType {
    case fast(value: Int, value2: Int)
    case middle(bool: Bool)
    case slow(string: String, string2: String)
}

案例fast使用数组,middle使用子字典,slow使用单独的键/值对。


然后声明MyStruct结构体,采用Codable并声明类型

struct MyStruct : Codable {
    var type : PostType

此解决方案需要自定义 key

  enum CodingKeys: String, CodingKey {
      case value, string, string2, middle
  }

encode 方法切换案例并创建适当的类型

  func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
      switch type {
      case .fast(let value, let value2) :
          try container.encode([value, value2], forKey: .value)

      case .slow(let string, let string2) :
          try container.encode(string, forKey: .string)
          try container.encode(string2, forKey: .string2)

      case .middle(let bool):
          try container.encode(["bool" : bool], forKey: .middle)
      }
  }

decode方法中,您可以通过传递的键来区分大小写,并确保它们是唯一的。

  init(from decoder: Decoder) throws {
      let values = try decoder.container(keyedBy: CodingKeys.self)
      let allKeys = values.allKeys
      if allKeys.contains(.middle) {
          let value = try values.decode([String:Bool].self, forKey: .middle)
          type = PostType.middle(bool: value["bool"]!)
      } else if allKeys.contains(.value) {
          let value = try values.decode([Int].self, forKey: .value)
          type = PostType.fast(value: value[0], value2: value[1])
      } else {
          let string = try values.decode(String.self, forKey: .string)
          let string2 = try values.decode(String.self, forKey: .string2)
          type = PostType.slow(string: string, string2: string2)
      }
   }
}

尽管有些键是硬编码的,但第一个选项似乎是最合适的。


最后一个使用它的示例:

let jsonString = "[{\"value\": [2, 6]}, {\"string\" : \"foo\", \"string2\" : \"bar\"}, {\"middle\" : {\"bool\" : true}}]"

let jsonData = jsonString.data(using: .utf8)!

do {
    let decoded = try JSONDecoder().decode([MyStruct].self, from: jsonData)
    print("decoded:", decoded)

    let newEncoded = try JSONEncoder().encode(decoded)
    print("re-encoded:", String(data: newEncoded, encoding: .utf8)!)

} catch {
    print(error)
}

关于json - 如何使用 Decodable 协议(protocol)将此 JSON 转换为 Swift 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44594459/

相关文章:

java - com.google.gson.internal.LinkedTreeMap 无法转换为我的类(class)

swift - 什么时候以及为什么一个类会成为 NSObject 的子类?

swift - 从命令行从 Objective-C header 生成 Swift 接口(interface)

swift 4 : struct in struct

swift - 如何在核心数据中使用 swift 4 Codable?

javascript - PHP json_encode 作为数组字符串返回,但未正确转换为 JavaScript 中的数组

javascript - 如何用js从json中赋值

arrays - 解开一个实际有值的可选时为零

Swift 4 Codable 从数组中获取第一个数组

javascript - NodeJS/JS 如何通过 sha256 正确散列对象 json 和字符串(串联)