【问题标题】:SWIFT: Iterate through a JSON object that's convert to a dictionarySWIFT:遍历转换为字典的 JSON 对象
【发布时间】:2020-09-14 15:25:38
【问题描述】:

注意:已经提出了一些类似的问题。然而,它们都没有提供如何解决这个看似简单的任务。所以我希望它在这里得到一劳永逸的解决。
我的问题: 我正在接收这个嵌套的 JSON 对象:

  print("type(of: JSON) \( type(of: JSON))") //__NSDictionaryI
  completion(true, nil, JSON as? [String: Any], nil)

如您所见,Alamofire 模块将其转换为字典。
我一直在尝试使用不同的方法(有些东西,我认为与 JavaScript 相比应该很简单)访问嵌套值几个小时,但我找不到一种可行的方法。
因此,除了高级值之外,我无法访问其他任何内容:

for (key,movieData) in moviesData! { // moviesData is the JSON dictionary object
    // Do some logic
   }

那么有没有办法轻松操作/访问接收到的 JSON 数据?

【问题讨论】:

标签: json swift


【解决方案1】:

这远不是一个理想的解决方案,但它确实有效。所以这里是:

  for (key,movieData) in moviesData! {
            if let nestedDictionary = moviesData![key] as? [String: Any] {
                print("nestedDictionary: ",nestedDictionary) // logs the result part of the JSON object
                // Trying to access nested values
                for (key,value) in nestedDictionary {
                    print("nestedDictionary.key: ",key)
                    print("nestedDictionary.type(of:value): ",type(of:value) )
                    print("nestedDictionary.value: ",value)
                    // Testing if sections is an array of dictionaries
                    if let arrayOfDictionaries = nestedDictionary[key] as? [[String: Any]] {
                        print("nestedDictionary: ",nestedDictionary) // logs the result part of the JSON object
                        // Trying to access array items which are sections
                        for item in arrayOfDictionaries {
                            print("arrayOfDictionaries.item: ",item)
                        }
                    }
                }
            }
        }

它基于here提到的提示:

if let dictionary = jsonWithObjectRoot as? [String: Any] {
    if let number = dictionary["someKey"] as? Double {
        // access individual value in dictionary
    }

    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
    }

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any] {
        // access nested dictionary values by key
    }
}

关键思想是检查json内部是否有嵌套字典或嵌套数组,然后进行相应的迭代。

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2015-09-09
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多