下面是我尝试解码的JSON的一个示例:
{
"results": [
{
"Modified": "2022-12-30T22:27:00",
"Published": "2022-12-23T15:15:00",
"access": {},
"assigner": "cve@mitre.org",
"cvss": null,
"cwe": "CWE-77",
"id": "CVE-2022-46642",
"impact": {},
"last-modified": "2022-12-30T22:27:00",
"references": [
"https://github.com/CyberUnicornIoT/IoTvuln/blob/main/d-link/dir-846/D-Link%20dir-846%20SetAutoUpgradeInfo%20command%20injection%20vulnerability.md",
"https://www.dlink.com/en/security-bulletin/"
],
"summary": "D-Link DIR-846 A1_FW100A43 was discovered to contain a command injection vulnerability via the auto_upgrade_hour parameter in the SetAutoUpgradeInfo function.",
"vulnerable_configuration": [
"cpe:2.3:o:dlink:dir-846_firmware:100a43:*:*:*:*:*:*:*",
"cpe:2.3:h:dlink:dir-846:a1:*:*:*:*:*:*:*"
],
"vulnerable_configuration_cpe_2_2": [],
"vulnerable_product": [
"cpe:2.3:o:dlink:dir-846_firmware:100a43:*:*:*:*:*:*:*"
]
},
(the JSON文件继续下一个{ "Modified"...
)
我搜索了一个解决方案,代码如下所示:
该结构体
struct CVE : Decodable
{
var id : String
var cvss : String? = nil
var Modified : String
var summary : String
}
struct CVEdata : Decodable
{
var results : [CVE]
}
JSON解码函数
func jsonDataRequest () async
{
if let url = URL(string: "https://cve.circl.lu/api/query?time_start=30-12-2022,time_end=31-12-2022")
{
do
{
let (data, _) = try await URLSession.shared.data(from: url)
arrCVE = try JSONDecoder().decode([CVEdata].self, from: data)
}
catch
{
print(error)
}
}
}
}
如果上面的算法是正确的,我如何访问arrCVE变量中的数据?我已经尝试过字典的for循环,但我认为问题出在解码行的某个地方。谢谢
1条答案
按热度按时间7kqas0il1#
这里的问题是JSON的顶层容器不是数组,因此解码类型应该是
CVEData.self
(而不是[CVEData].self
)。然后您可以通过
arrCVE.results
访问CVE对象列表。不要忘记,必须相应地重新声明
arrCVE
:var arrCVE: CVEdata?