json - 转换 JSON 对象以从中提取数据时出错

标签 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)

     }
}

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

我需要使用什么类型来解压数据?

最佳答案

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

关于json - 转换 JSON 对象以从中提取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915498/

相关文章:

android - 使用JSON从Android应用程序向Django服务器发送/接收.wav文件

java - 通过类名反序列化json

ios - Swift iOS - 如何找到 CollectionView 第二部分的 CGPoint x/y 值

iOS11 用户位置不显示蓝色标记

c++ - 如何判断模板类型是基本类型还是类

json - 当错误 400(错误请求)发生时,使用 Axios 捕获 POST 返回的 json

c# - 看似有效的 JSON Blob 的 JSON.NET 反序列化失败

具有泛型方法的 Swift 协议(protocol) : invalid redeclaration of implementation

c# - 获取特定类中使用的类型

class - 为什么 Manifest 在构造函数中不可用?