【发布时间】:2023-03-10 23:17:01
【问题描述】:
我有一些像这样的 JSON
[
{
"schema_name": "major_call",
"schema_title": "Major Call",
"schema_details": [
{
"dataname": "call_number",
"title": "Call Number",
"datatype": "viewtext"
},
以及一些处理它的代码
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [[String:Any]]
for i in 0 ..< json.count{
let schema_name: String = json[i]["schema_name"] as? String ?? "" //works fine!
print(schema_name)
// error: Contextual type '[String : Any]' cannot be used with array literal
let blob: [String:Any] = json[i]["schema_details"] as? [String:Any] ?? [""]
for j in 0 ..< blob.count{ //this is all I want to do!
// errror: Cannot subscript a value of type '[String : Any]' with an index of type 'Int'
let data_name: String = blob[j]["dataname"] as? String ?? ""
print(schema_name + "." + data_name)
}
}
但它不会解析嵌套对象。我在标记的行上收到错误,表明对象的类型不正确。
我需要使用哪些类型来解压数据?
【问题讨论】:
-
提示:
json[i]["schema_details"]返回一个字典数组,就像您的 JSON 的顶层一样。 -
仅此而已吗?
let blob = json[i]["schema_details"]你真是个天才 -
鉴于您使用的是 Swift 4,我会强烈推荐使用新的
CodableAPI 和JSONDecoder。