【问题标题】:How to convert model with array to JSON array Swift 3如何将带有数组的模型转换为 JSON 数组 Swift 3
【发布时间】:2018-12-08 04:47:56
【问题描述】:

我有一些问题和解决方案,我有类模型,里面有数组,我的模型是这样的

class WillModel{
    var name: String = ""
    var documents:[WillItems] = []
    var isLFStatus : Bool = false
    var isLFShared : Bool = false
}

class WillItems{
    var documentPath: String = ""
    var documentRemark: String = ""
}

我想将结果转换为 JSON 数组,如

{
 "name" : "value",
 "documents" : [
      {
       "documentPath" : "value"
       "documentRemark" : "value"
       },
      {
       "documentPath" : "value2"
       "documentRemark" : "value2"
      }
      ],
 "isLFStatus" : true,
 "isLFShared" : true
}

我正在使用 Swift 3,感谢您的解决方案

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我强烈建议更新到 Swift 4 并采用CodableJSONEncoder 可以分两行完成。

标签: arrays json swift swift3


【解决方案1】:

您可以编写一个简单的方法来手动将encode 您的model 转换为json,如下所示,

func encodeWillModel(_ model: WillModel) -> [String: Any] {
    var params: [String: Any] = [:]
    params["name"] = model.name
    params["documents"] = model.documents.map({["documentPath": $0.documentPath,
                                                "documentRemark": $0.documentRemark]})
    params["isLFStatus"] = model.isLFStatus
    params["isLFShared"] = model.isLFShared
    return params
}

您可以传递任何模型来获取类似的 json,

let willModelJSON = encodeWillModel(yourModel)

但更好的方法是使用任何支持Swift 3json 解析库(ObjectMapper)或升级到Swift 4 并使用Encodable/Decodable

【讨论】:

  • @j.lo 您想确认上述建议的解决方案是否适合您?如果是,您能否接受答案以帮助其他人知道它有效。否则,如果您遇到任何问题,请告诉我们。
猜你喜欢
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
相关资源
最近更新 更多