arrays - 如何将带有数组的模型转换为 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,感谢您的解决方案
解决方案
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
解析库(SwiftyJSON、ObjectMapper )Swift 3
Swift 4
Encodable/Decodable
推荐阅读
- c - Else 语句在 strcmp 中返回错误结果(比较哈希值)(更新)
- javascript - 为什么 jQuery-migrate 不直接在代码中替换折旧的函数?
- prolog - SWI Prolog CLP(FD) 调度
- tomcat - 如何在 EL Stream API 中使用 Collectors#joining?
- dask - dask 数据框的 read_csv 无法正确读取 csv
- linux - 将 rsa 密钥部署到其他机器
- ios - 用于注册的 gmail 集成
- java - 按名称、居住者和大小对国家/地区的 ArrayList 进行排序
- flutter - 如何在我不知情的情况下检查使用广告 ID 的依赖项
- go - 从未触发 if 语句使基准测试中的代码执行更快?为什么?