【问题标题】:Errors casting JSON object to extract data from it转换 JSON 对象以从中提取数据时出错
【发布时间】: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,我会强烈推荐使用新的 Codable API 和 JSONDecoder

标签: json swift types casting


【解决方案1】:

schema_details 的值是一个数组,而不是字典。

为了清楚起见,让我们使用类型别名并删除丑陋的基于 C 样式索引的循环

typealias JSONArray = [[String:Any]]

if let json = try JSONSerialization.jsonObject(with: data) as? JSONArray {
    for schema in json {
        let schemaName = schema["schema_name"] as? String ?? ""
        print(schemaName)
        if let details = schema["schema_details"] as? JSONArray {  
            for detail in details { 
                let dataName = detail["dataname"] as? String ?? "" 
                print(schemaName +  "." + dataName)
            }
        }
    }
}

【讨论】:

  • vadian 太好了,我现在有一个小问题,我需要稍后将字典的一部分字符串化以进行缓存,如何将 detail 变成 Data: 所需的 String(data:, encoding: .utf8)编码?
  • detail 是一本字典。您可以使用 JSONSerialization 做相反的事情并将字典序列化为代表 JSON 字符串的 Data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多