抛出JSON对象以从中提取数据的错误

时间:2017-10-24 16:23:04

标签: json swift types casting

我有一些看起来像这样的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)

     }
}

但它不会解析嵌套对象。我在标记的行上出错,表示对象的类型不正确。

我需要使用哪些类型来解压缩数据?

1 个答案:

答案 0 :(得分:3)

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)
            }
        }
    }
}