【问题标题】:How to parse several hardcoded keys in JSON API struct with Swift Decodable protocol?如何使用 Swift Decodable 协议解析 JSON API 结构中的几个硬编码键?
【发布时间】:2018-06-05 18:50:02
【问题描述】:

问题:我正在尝试解码我​​的 JSON,其中一些 JSON 将具有随机字符串,而另一些将具有硬编码字符串。当硬编码字符串是以下之一时,我想显示不同的 UICollectionView 单元格。如果我的 JSON 是硬编码字符串并且能够用它显示不同的 UICollectionViewCell,我在尝试解析我的 JSON 时遇到问题。对此的任何帮助都会很棒。这可能是一个初学者的问题,但我在过去一周试图解决这个问题,但我很难做到。对此的任何帮助将不胜感激。

**  Hardcoded Strings that could be one or the other:**
key: --> This string could be "breaking" or "normal" or "new"
item: --> This string could be "placement" or "slot" or "shared"
verb: --> This string could be "shared" or "posted"

** NOT hardcoded strings, which the string comes in randomly**
heading: --> This string is a random string
type: --> This string is a random string

这是我的一些 JSON,因此您可以获取我正在尝试做的示例:

    {
    slots: [
        {
        key: "breaking",
        item: "placement",
        heading: "Random String Text",
        type: "Random String Text",
        via: "Random",
        verb: "shared"
        sort_order: 0
        },
        {
        key: "breaking",
        item: "placement",
        heading: "Random String Text",
        type: "Random String Text",
        via: "Random",
        verb: "posted"
        sort_order: 1
        },
        {
        key: "event",
        item: "combine",
        heading: "Random String Text",
        type: "Random String Text",
        via: "Random",
        verb: "posted"
        sort_order: 2
        },
}

这是我迄今为止为我的模型所做的:

struct MyModel: Decodable {
    var key: String?
    var item: String?
    var heading: String?
    var type: String?
    var via: String?
    var verb: String?
}

这是 Dmitry Serov 帮助我完成的一个示例单元格。

func collectionView(_ collectionView: UICollectionView,
 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

   let model = ... // retrieve your model object here
   if model.verb == .shared {
     // Pass the pertinent identifier
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier:...)
     return cell
   else {
     ....
   }
 }

这是 Dmitry Serov 帮助我编写的更多代码。

struct MyModel { // Type names should use pascal case in Swift
  var verb: State?
  ....
  enum State {
    case shared
    case posted
  }
}

// Decode your enums from strings
extension MyModel.State: Decodable {
  enum CodingKeys: String, CodingKey {
    case shared
    case posted
  }
}

当我尝试上面的问题时,它要求我输入下面的格式,我不知道该怎么做,我正在尝试解析更多的键。

extension MyModel.State: Decodable {
    init(from decoder: Decoder) throws {

  }
}

【问题讨论】:

    标签: json swift parsing swift4


    【解决方案1】:

    这是我使用可编码解码您的 json 的方式:

    struct Response: Codable {
        var slots = [Slots]()
    }
    
    struct Slots: Codable {
        var key: String?
        var item: String?
        var heading: String?
        var type: String?
        var via: String?
        var verb: String?
        var order: String?
    
        enum CodingKeys: String, CodingKey {
            case order = "sort_order"
        }
        /** Custom Encoder to send null values**/
        func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
    
            try? container.encode(order, forKey: .order)
        }
    
    }
    

    要与硬编码字符串进行比较,请创建一个枚举:

    enum key: String {
        case breking
        case normal
        case new
    }
    

    像这样使用它:

    if let response = try? JSONDecoder().decode(Response.self, from: response.data!){
    for slot in response.slots{
        if slot.key == key.breaking.rawValue{
        //do something
        }
    }
    }
    

    【讨论】:

    • 感谢您,但在此代码中不显示任何硬编码字符串,也不能根据我上面所述的硬编码字符串显示不同的 UIcollectioview 单元格...
    • 谢谢!我会尝试。如何为此创建扩展程序?我在哪里放置“枚举键:”和 if let response = try? ...”。我在哪里把它放在代码中?
    • 我想您是从服务器获取 JSON 的,对吧?...在​​您的服务器响应中放置 JSONDecoder,然后您可以从那里将其传递给您的视图控制器,在您的 UIVIewCollection 委托函数上放置if 比较
    • 我需要扩展这个还是你放的代码没问题?我是否只是将“if let response = try?...”添加到 UICollectionView 控制器中?
    • 是的,我是从服务器获取的。我们可以继续 stackoverflow 聊天吗?
    猜你喜欢
    • 2017-11-16
    • 2017-11-19
    • 1970-01-01
    • 2021-08-07
    • 2020-02-09
    • 2018-10-30
    • 2021-07-06
    • 1970-01-01
    • 2019-03-13
    相关资源
    最近更新 更多