简体   繁体   English

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

[英]How do I convert this JSON into a Swift structure using the Decodable protocol?

Note : I have already looked at this question -> How do I use custom keys with Swift 4's Decodable protocol? 注意 :我已经看过这个问题-> 如何在Swift 4的Decodable协议中使用自定义键? But it does not explain how to Encode/Decode enums 但是它没有解释如何对枚举进行编码/解码

Here is the structure I want: 这是我想要的结构:

struct MyStruct: Decodable {
    let count: PostType
}

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

Now i know how i want my struct to look, the problem is: 现在我知道我希望我的结构看起来如何,问题是:

  1. I do not know what the init function should look like inside of the PostType enum. 我不知道init函数在PostType枚举内部应该是什么样子。

I use the code below to help me construct the JSON quickly. 我使用下面的代码来帮助我快速构造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)
    }

Can anyone help me with this? 谁能帮我这个?

Edit1 my JSON looks like this Edit1我的JSON看起来像这样

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

What should the init look like in the PostType enum ? initPostType enum应该是什么样子?

Since an enum with associated types does not match any JSON type you need a bit more handwork and write a custom mapping. 由于具有关联类型的enum与任何JSON类型都不匹配,因此您需要更多的工作并编写自定义映射。

The following code covers three options. 以下代码涵盖了三个选项。

  • A dictionary with the case as key and an containing dictionary with parameter labels as keys 以大小写为键的字典和以参数标签为键的包含字典
  • Encoding / Decoding each associated value as separate key / value pair 将每个关联值编码/解码为单独的键/值对
  • Encoding / Decoding all associated values in an array with an arbitrary key. 使用任意键对数组中的所有关联值进行编码/解码。

First of all the enum must not conform to Codable 首先,枚举必须不符合Codable

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

The case fast uses an array, middle a sub-dictionary, slow separate key / value pairs. fast使用一个数组, middle一个子字典, slow单独的键/值对。


Then declare the MyStruct struct, adopt Codable and declare the type 然后声明MyStruct结构,采用Codable并声明type

struct MyStruct : Codable {
    var type : PostType

This solution requires custom keys 此解决方案需要自定义键

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

The encode method switch es on the cases and creates the appropriate types 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)
      }
  }

In the decode method you can distinguish the cases by the passed keys, make sure that they are unique. 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)
      }
   }
}

Although some keys are hard-coded the first option seems to be the most suitable one. 尽管有些键是硬编码的,但第一个选项似乎是最合适的。


Finally an example to use it: 最后是一个使用它的示例:

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM