首页 > 解决方案 > 如何将带有数组的模型转换为 JSON 数组 Swift 3

问题描述

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

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,感谢您的解决方案

标签: arraysjsonswiftswift3

解决方案


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)

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


推荐阅读