json - 快速访问 json 的内部信息
问题描述
我检索了我的数据,但我需要的数据在第一个值“0”中,所以我如何访问“价格”或“产品名称”之类的东西
["0": {
price = "4.77";
productname = "KISSES Giant Milk Chocolate Candy, 7 oz";
}]
URLSession.shared.dataTask(with: url!) { (data, response, err) in
guard let data = data else {return}
do {
let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
print(json)
} catch let jsonErr {
}
}.resume()
解决方案
正如评论中提到的,不要使用JSONSerialization
,使用Decodable
。
使用 CodingKeys很容易将其转换为合法的结构成员名称"0"
struct Root: Decodable {
let zero: Product
private enum CodingKeys : String, CodingKey { case zero = "0" }
}
struct Product: Decodable {
let price, productname : String
}
...
let jsonString = """
{"0":{"price":"4.77","productname":"KISSES Giant Milk Chocolate Candy, 7 oz"}}
"""
let data = Data(jsonString.utf8)
do {
let result = try JSONDecoder().decode(Root.self, from: data)
print(result.zero.productname)
} catch { print(error) }
推荐阅读
- go - 为什么要在 Golang 中声明相同的变量?
- c++ - 我可以从 Windows RECT 结构访问宽度和高度而不计算它吗?
- regex - 正则表达式 - 匹配 URL,但不是更深层次
- azure - 如何在不使用 Visual Studio Code 中的 git 的情况下将我的 ASP.Net Core Angular Web 应用程序发布到 Azure
- aws-lambda - 一个或多个参数值无效:键 xyz 的类型不匹配预期:S 实际:M
- python - 在工作日的工作时间内绘制时间序列的百分位数
- reactjs - 使 React AppBar 和 SplitPane 适合没有滚动条
- c++ - 使用 Visual Studio 调试时如何查看 C++ 模板参数?
- html - 不存在导航项时隐藏引导汉堡图标
- python-3.7 - __init__() 在进行迁移时缺少 2 个必需的位置参数:“from_fields”和“to_fields”