ios - 是否可以为普通的 kv json 创建 Swift Codable?
问题描述
我有 JSON 数据,例如:
{
"peopleA": "nnll",
"peopleB": "ihyt",
"peopleC": "udr",
"peopleD": "vhgd",
"peopleE": "llll"
}
有成千上万这样的数据,基本上我想做的是读取 JSON 文件,并获取相关信息,例如: input peopleC
, return udr
。
尝试使用一些在线解决方案,我得到了
struct Welcome: Codable {
let peopleA, peopleB, peopleC, peopleD: String
let peopleE: String
}
我知道我可以将 JSON 文件重构为:
{
"candidates": [
{
"name": "peopleA",
"info": "nnll"
},
{
"name": "peopleB",
"info": "ihyt"
},
{
"name": "peopleC",
"info": "udr"
}
]
}
并获取相关的 Swift 结构:
struct Welcome: Codable {
let candidates: [Candidate]
}
// MARK: - Candidate
struct Candidate: Codable {
let name, info: String
}
我只是想知道我们是否可以在不对 json 文件进行后处理的情况下使其在 Swift 中工作?
解决方案
您可以简单地将其解码为字典。然后,如果您愿意,可以将您的字典映射到您的候选结构数组中:
struct Welcome: Codable {
let candidates: [Candidate]
}
struct Candidate: Codable {
let name, info: String
}
let js = """
{
"peopleA": "nnll",
"peopleB": "ihyt",
"peopleC": "udr",
"peopleD": "vhgd",
"peopleE": "llll"
}
"""
do {
let dictionary = try JSONDecoder().decode([String: String].self, from: Data(js.utf8))
let welcome = Welcome(candidates: dictionary.map(Candidate.init))
print(welcome)
} catch {
print(error)
}
这将打印:
欢迎(候选人:[候选人(姓名:“peopleA”,信息:“nnll”),候选人(姓名:“peopleC”,信息:“udr”),候选人(姓名:“peopleB”,信息:“ihyt”),候选人(姓名:“peopleE”,信息:“llll”),候选人(姓名:“peopleD”,信息:“vhgd”)])
推荐阅读
- android - 如何使颤振应用程序响应?
- r - 扫描一列以查找超过某个值的值,并将整个列移动到 R 中的新数据框中
- spring - Spring Framework:由于浏览器中的多个选项卡而获取错误的 processFormSubmission() 对象
- javascript - 模糊时 SSN 的 Angular UI 掩码
- android - 无法解决 play-service-places-placereport
- scala - 如何使用 Spark 在 Scala 中返回多列键和值对
- php - 当我将我的 webapp 上传到 linux 服务器时,laravel 页面无法正常工作
- hadoop - 如何获取 hdfs 文件上最后添加的数据?
- powershell - 通过 Powershell 添加到 AD。错误
- twitter-bootstrap-3 - Bootstrap carousel 和 show 根据当前幻灯片显示不同的文本和文本动画