我怎样才能解决这个问题?从“[String]”转换为无关类型“[String : AnyObject]”总是失败

How can I fix this? Cast from '[String]' to unrelated type '[String : AnyObject]' always fails

我似乎找不到这个问题的解决方案,有数百个答案,但 none 我可以找到与这个简单问题相关的答案。 无论我做什么来尝试将字典放入字符串中,都失败了吗? 原文:

let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let jsonString = (jsonResult as AnyObject).components(separatedBy: "")                           
let jsonDict = jsonString as! [String: AnyObject]
//let jsonDict = jsonString as! [String: AnyObject]
//let jsonDict = jsonString as! Dictionary<String,String>
//Cast from '[String]' to unrelated type 'Dictionary<String, String>' always fails 

完整代码,@Vadian 修复后现在可以正常工作了。

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    searchForMovie(title: "pulp_fiction")
}

func searchForMovie(title: String){
    //http://www.omdbapi.com/?t=pulp+fiction
    if let movie = title.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed){
        let url = URL(string: "https://www.omdbapi.com/?t=\(movie)&i=xxxxxxxx&apikey=xxxxxxxx")
        // this url contains the omnbapi keys which are free/

        let session = URLSession.shared
        let task = session.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error!)
            } else {
                if data != nil {
                    do {
                       let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                       if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
                            let jsonArray = jsonResult.components(separatedBy: "")
                            print(jsonArray)
                        } else {
                            print("This JSON is (most likely) not a string")
                        }

                       let jsonDict = jsonResult as! [String: Any]

                        DispatchQueue.main.async {
                        print(jsonDict)
                        }
                    } catch {
                    }
                }
            }
        })
        task.resume()
    }
}
}

结果是:

This JSON is (most likely) not a string
["Poster": https://m.media-

amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg, "BoxOffice": N/A, "Language": English, Spanish, French, "Year": 1994, "Metascore": 94, "Director": Quentin Tarantino, "Rated": R, "Runtime": 154 min, "Genre": Crime, Drama, "imdbVotes": 1,548,861, "Ratings": <__NSArrayI 0x604000256a10>(
{
    Source = "Internet Movie Database";
    Value = "8.9/10";
},
{
    Source = "Rotten Tomatoes";
    Value = "94%";
},
{
    Source = Metacritic;
    Value = "94/100";
}
)
, "Released": 14 Oct 1994, "imdbRating": 8.9, "Awards": Won 1 Oscar. Another 62 wins & 69 nominations., "Actors": Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta, "Response": True, "Country": USA, "Plot": The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption., "DVD": 19 May 1998, "Title": Pulp Fiction, "Writer": Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino, "Production": Miramax Films, "imdbID": tt0110912, "Website": N/A, "Type": movie]

首先,从不 使用 AnyObject 作为 JSON 值 Swift 3+。他们都是Any.

错误发生是因为components(separatedBy的结果是一个数组([String]),但是你把它转换成一个字典([String:Any(Object)])。根本不要转换,编译器知道类型。

并且不要在 Swift 中使用 .mutableContainers,永远不要。这个选项没有意义。

components(separatedBy 只有在 JSON 是字符串时才有意义。如果是这样,您必须传递选项 .allowFragments

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
   let jsonArray = jsonResult.components(separatedBy: "") 
   print(jsonArray)
} else {
    print("This JSON is (most likely) not a string")
} 

编辑:

根据您添加的结果,接收到的对象显然是一个字典,因此 as? String 以及 components(separatedBy:.allowFragments 都是错误的。试试这个

if let jsonDictionary = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
   for (key, value) in jsonDictionary {
       print(key, value)
   }
} else {
    print("This JSON is not a dictionary")
}