如何使用Decodable协议将此JSON转换为Swift结构?

swi*_*nub 2 json swift codable

注意:我已经看过这个问题 - > 如何在Swift 4的可解码协议中使用自定义键?但它没有解释如何编码/解码枚举

这是我想要的结构:

struct MyStruct: Decodable {
    let count: PostType
}

enum PostType: Decodable {
    case fast(value: Int, value2: Int)
    case slow(string: String, string2: String)
}
Run Code Online (Sandbox Code Playgroud)

现在我知道我希望我的结构看起来如何,问题是:

  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)
    }
Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?

Edit1我的JSON看起来像这样

   {
        "count": {
           "fast" :
            {
                "value": 4,
                "value2": 5
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

应该是init什么样的PostType enum

vad*_*ian 5

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

以下代码包含三个选项.

  • 一个字典,其中案例为键,包含字典,参数标签为键
  • 将每个相关值编码/解码为单独的键/值对
  • 使用任意键对数组中的所有关联值进行编码/解码.

首先,枚举必须符合 Codable

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

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


然后声明MyStruct结构,采用Codable并声明type

struct MyStruct : Codable {
    var type : PostType
Run Code Online (Sandbox Code Playgroud)

此解决方案需要自定义键

  enum CodingKeys: String, CodingKey {
      case value, string, string2, middle
  }
Run Code Online (Sandbox Code Playgroud)

encode方法switch用于案例并创建适当的类型

  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)
      }
  }
Run Code Online (Sandbox Code Playgroud)

在该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)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

虽然有些键是硬编码的,但第一种选择似乎是最合适的.


最后一个使用它的例子:

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)
}
Run Code Online (Sandbox Code Playgroud)